SlideShare a Scribd company logo
1 of 54
Download to read offline
Replication Tips & Tricks                                                                                                       + some things about GTIDs
Mats Kindahl
mats.kindahl@oracle.com




 1Copyright © 2012, Oracle and/or its affiliates. All rights reserved.   Insert Information Protection Policy Classification from Slide 12
Program Agenda


     Replication setup and status checking
     Slave fail-over using GTID
     Binary log analysis
     Crash-safe slaves
     Multi-source replication



2   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
About the Presentation



            This presentation will introduce you to some replication
            features and also briefly show tips and tricks on how to
            work with replication. The focus is on short ideas and
            each item does not go deeper into details.




3   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
What is Replication?


       ●      MySQL Master Server
                 –      Changes data
                 –      Sends changes to slave
       ●      MySQL Slave Server
                 –      Receives changes from master
                 –      Applies received changes to
                        database



4   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Replication Topologies



    Dual Master
                                                                           Circular

                                                                                      Tree
Simple




5   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Why Replication?
      Scaling out

                                                                           Writes




                                                                           Reads




6   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Why Replication?
      Redundancy



                                                                             Slave
                          Crash                                            Promotion




                                                                                       New Master




7   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Replication Architecture
                                                                     Master   Slave




8   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Reading Slave Status
      Understanding the fields of SHOW SLAVE STATUS



       ●      I/O Thread Status                                            ●   SQL Thread Status
                 –      Slave_IO_Running                                       –   Slave_SQL_Running
                 –      Last_IO_Errno                                          –   Last_SQL_Errno
                 –      Last_IO_Error                                          –   Last_SQL_Error
                 –      Last_IO_Error_Timestamp                                –   Last_SQL_Error_Timestamp
       ●      Master being replicated from
                 –      Master_Host
                 –      Master_Port

9   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Reading Slave Status
       Understanding the fields of SHOW SLAVE STATUS



        ●      Next event to execute – in master log coordinates
                  –      Relay_Master_Log_File + Exec_Master_Log_Pos
        ●      Next event to execute – in relay log coordinates
                         Relay_Log_File + Relay_Log_Pos
        ●      Next event to read from master
                         Master_Log_File + Read_Master_Log_Pos




10   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Reading the Binary Log
         Decoding the binary log



          ●      Use mysqlbinlog
                           --hexdump                                  Show hex dump of event as comment
                           --start-position Start dumping at a position
                           --stop-position Stop dumping after this position

     # at 275                                                                              175 =373
                                                                                              16   10
     #120927 23:11:58 server id 3                                         end_log_pos 373
     # Position Timestamp    Type                                          Master ID        Size        Master Pos    Flags
     #      113 1e c1 64 50   02                                          03 00 00 00   62 00 00 00     75 01 00 00   00 00

                                                                                      Little-endian
                                                                              Query
11     Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Reading the Binary Log
         Decoding the binary log




     # at 275
     #120927 23:11:58 server id 3 end_log_pos 373
     # Position Timestamp    Type    Master ID        Size      Master Pos     Flags
     #      113 1e c1 64 50   02    03 00 00 00   62 00 00 00   75 01 00 00    00 00
     #      126 c5 03 00 00 00 00 00 00 04 00 00 1a 00 00 00 00 |................|
     #      136 00 00 01 00 00 00 00 00 00 00 00 06 03 73 74 64 |.............std|
     #      146 04 21 00 21 00 08 00 74 65 73 74 00 69 6e 73 65 |.......test.inse|
     #      156 72 74 20 69 6e 74 6f 20 74 32 20 76 61 6c 75 65 |rt.into.t2.value|
     #      166 73 20 28 31 2c 27 74 65 73 74 69 6e 67 27 29       |s..1..testing..|
     #        Query  thread_id=965    exec_time=0     error_code=0
     SET TIMESTAMP=1348780318/*!*/;
     insert into t2 values (1,'testing')
     /*!*/;

12     Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Reading the Binary Log
          Decode row events



           ●      Use mysqlbinlog
                            --verbose                                  Decode row events into pseudo-SQL
     # at 849
     # at 893
     #120928 15:19:24 server id 3                                end_log_pos 893   Table_map: `test`.`t2` mapped to number 48
     #120928 15:19:24 server id 3                                end_log_pos 941   Write_rows: table id 48 flags: STMT_END_F

     BINLOG '
     3KNlUBMDAAAALAAAAH0DAAAAADAAAAAAAAEABHRlc3QAAnQyAAIDDwIoAAM=
     3KNlUBcDAAAAMAAAAK0DAAAAADAAAAAAAAEAAv/8AwAAAA1yb3dzIGFyZSBjb29s
     '/*!*/;




13      Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Reading the Binary Log
          Decode row events



           ●      Use mysqlbinlog
                            --verbose                                  Decode row events into pseudo-SQL
     # at 849
     # at 893
     #120928 15:19:24 server id 3                                end_log_pos 893   Table_map: `test`.`t2` mapped to number 48
     #120928 15:19:24 server id 3                                end_log_pos 941   Write_rows: table id 48 flags: STMT_END_F

     BINLOG '
     3KNlUBMDAAAALAAAAH0DAAAAADAAAAAAAAEABHRlc3QAAnQyAAIDDwIoAAM=
     3KNlUBcDAAAAMAAAAK0DAAAAADAAAAAAAAEAAv/8AwAAAA1yb3dzIGFyZSBjb29s
     '/*!*/;
     ### INSERT INTO test.t2
     ### SET
     ###   @1=3
     ###   @2='rows are cool'

14      Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Global Transaction Identifiers (GTIDs)
        Handling positions in MySQL 5.5



        ●      Binary log positions manually handled
        ●      Each server has it's own position
        ●      Failing over slaves to new masters difficult
                  –      What is the position to fail over to?

       CHANGE MASTER TO
          MASTER_HOST='master1.example.com', MASTER_PORT=3306,
          MASTER_USER='repl_user', MASTER_PASSWORD='xyzzy',
          MASTER_LOG_FILE='master-bin.00001', MASTER_LOG_POS=22145;
                                                                             Different for
                                                                            different servers
15   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Global Transaction Identifiers (GTIDs)
       Enabling Global Transaction IDs



       ●     MySQL 5.6 has Global Transaction ID
               –      Positions independent of server
       ●     GTID handshake
               –      Done on connection with master
               –      Negotiate position automatically



        CHANGE MASTER TO
           MASTER_HOST='master1.example.com', MASTER_PORT=3306,
           MASTER_USER='repl_user', MASTER_PASSWORD='xyzzy',
           MASTER_LOG_FILE='master-bin.00001', MASTER_LOG_POS=22145;
           MASTER_AUTO_POSITION=1;

16   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Global Transaction Identifiers (GTIDs)
       Enabling Global Transaction IDs



        ●      Turn on GTIDs                                                [mysqld]
                                                                            …
        ●      Turn off dangerous statements                                gtid-mode=on
                 –      CREATE TABLE...SELECT                               enforce­gtid­consistency=on
                                                                            log-bin=master-bin
                 –      CREATE TEMPORARY TABLE                              log-slave-updates
                            ●     Inside transactions

        CHANGE MASTER TO
           MASTER_HOST='master1.example.com', MASTER_PORT=3306,
           MASTER_USER='repl_user', MASTER_PASSWORD='xyzzy',
           MASTER_LOG_FILE='master-bin.00001', MASTER_LOG_POS=22145;
           MASTER_AUTO_POSITION=1;

17   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Global Transaction Identifiers (GTIDs)
       Global Transaction ID Concepts



        ●      Global transaction ID
                  –      A server UUID + Transaction Number
                             a61678ba­4889­4279­9e58­45ba840af334:1
                  –      Preserved when replicated
        ●      Global Transaction ID Set
                  –      Sequence of Server UUID + Transaction Number Range
                            a61678ba­4889­4279­9e58­45ba840af334:1­5,
                            f88e2a43­a13e­11e2­98de­0021cc6850ca:12­2564


18   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Global Transaction Identifiers (GTIDs)
       Server Variables



        ●      @@GTID_EXECUTED
                  –      GTID set of all transactions logged in the binary log
        ●      @@GTID_PURGED
                  –      GTID set of all transaction purged from binary log
                  –      Cannot be sent to slaves




19   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Cloning a Slave
                                                                                   Be
                                                                               My    fo
       Creating a slave image                                                     SQ   re
                                                                                    L
                                                                                      5.
        1. Stop the slave                                                               6
        2. Write down where slave has stopped
                  –      SHOW SLAVE STATUS
                  –      Relay_Master_Log_File + Exec_Master_Log_Pos
        3. Backup slave
                  –      mysqldump – slow but safe
                                   ­­dump­slave Generate CHANGE MASTER
                  –      Physical file copy – fast but you need to shut down the server

20   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Cloning a Slave
                                                                                Be
                                                                            My     fo
       Setting up the new slave                                                SQ    re
                                                                                  L
                                                                                    5.
        4. Restore backup on new slave                                                6
        5. Direct the slave to the master
                  –      CHANGE MASTER
                  –      Master_Host + Master_Port
                  –      Relay_Master_Log_File + Exec_Master_Log_Pos
        6. Start slave
                  –      START SLAVE



21   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Cloning a Slave
                                                                                               My
                                                                                                 SQ
                                                                                              or     L
                                                                                                       5
        1. Stop the slave                                                                         lat .6
                                                                                                     er
        2. Backup slave
                         mysqldump ­­host=slave1.example.com ­­user=root 
                            ­­dump­slave ­­set­gtid­purged >image.sql
        3. Start the slave
                                                                            Tell slave that transactions
        4. Restore image on new slave
                                                                            in image cannot be replicated
                         mysql ­­host=slave2.example.com ­­user=root <image.sql
        5. Start Slave



22   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Point in time recovery


        ●      Use mysqlbinlog
                         --to-datetime                              Stop reading when reaching date
        ●      Example
                         mysqlbinlog --read-from-remote-server   
                                                                                    e
                             --host=master -uroot --position=192                ar      !
                             --to-datetime=”2009-04-11 12:36:56”             ps      ing
                                                                            am reas
                                                                         st
                             master-bin.00002[2-4] |                   e      nc
                         mysql -uroot --host=slave                  tim lly i
                                                                  :      a
                                                                                                 ing   ic
                                                                                              r n ot on
                                                                                           W a on
                                                                                                m
                                                                                          not

23   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Using Relay Servers


        ●      Relieve master server by
               creating relay slaves
        ●      Just keep binary logs
        ●      Do not store data in tables
                  –      Use BLACKHOLE engine
                  –      --log-slave-updates

                SET STORAGE_ENGINE = BLACKHOLE
                ALTER TABLE table ENGINE = BLACKHOLE


24   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Using Relay Servers

                                                       replicate-wild-do-table=*.%_east   replicate-wild-do-table=*.%_west


        ●      Filtering replication stream
        ●      Filtering done on relay servers
        ●      replicate­wild­*­table
                  –      Work with cross-database
                         queries




25   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Write Your Own Library
       Write your own utility library

        ●      Create a utility library to easier work with replication
        ●      Common functions to manage replication:
                  –      Start/stop slave
                  –      Change master
                  –      Fetch master position
                  –      Fetch slave execute/read position
                  –      Fetch master host information



26   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Write Your Own Library
       Basic functions using Bourne shell

       # Usage: mysql_exec socket sql ...                                   # Usage: stop_slave socket [ thread ]
       mysql_exec () {                                                      stop_slave () {
           sock=$1                                                             mysql_exec $1 STOP SLAVE $2
           shift 1                                                          }
           mysql ­uroot ­­vertical ­­batch 
               ­­skip­column­names                                         # Usage: start_slave socket [ thread ]
               ­­socket="$sock"                                            start_slave () {
               ­­exec "$*"                                                     mysql_exec $1 START SLAVE $2
       }                                                                    }




27   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Write Your Own Library
       Basic functions using Bourne shell

       # Usage: change_master socket [ host [ port [ file [ pos ] ] ] ]
       change_master () {
           host=${2:+MASTER_HOST='$2'}
           port=${3:+,MASTER_PORT=$3}
           file=${4:+,MASTER_LOG_FILE='$4'}
           pos=${5:+,MASTER_LOG_POS=$5}
           mysql_exec $1 CHANGE MASTER TO $host $port $file $pos
       }

       # Usage: fetch_master_pos socket
       fetch_master_pos () {
          mysql_exec $1 SHOW MASTER STATUS |
          grep '<File|<Pos'             |
          cut ­f2 ­d:
       }



28   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Write Your Own Library
       Basic functions using Bourne shell

       # Usage: fetch_slave_exec_pos socket
       fetch_slave_exec_pos () {
          mysql_exec $1 SHOW SLAVE STATUS |
          grep '<Relay_Master_Log_File|<Exec_Master_Log_Pos' |
          cut ­f2 ­d:
       }

       # Usage: fetch_slave_read_pos socket
       fetch_slave_read_pos () {
          mysql_exec $1 SHOW SLAVE STATUS |
          grep '<Master_Log_File|<Read_Master_Log_Pos' |
          cut ­f2 ­d:
       }




29   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
master1.example.com   master2.example.com
     Round-Robin Replication


        ●      Slave can only replicate from single
               master at a time
        ●      Use time sharing to replicate from
               several masters
                                          Stop

                                                                            Switcher
                       Start                                 Save

                                                                                            slave1.example.com
                                       Restore

30   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Round-Robin Replication
       A version using Bourne Shell

       # Usage: fetch_host_and_pos socket
       fetch_host_and_pos () {
           mysql_exec $1 SHOW SLAVE STATUS |
           grep '<Master_(Host|Port|Log_File)|<Read_Master_Log_Pos' |
           cut -f2 -d:
       }

       # Usage: stop_and_save socket
       stop_and_save () {
         sock="/var/run/mysqld/$1.sock"
         stop_slave $socket
         fetch_host_and_pos $sock >$1.savepos
       }




31   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Round-Robin Replication
       A version using Bourne Shell

       restore_and_start () {                                               cnt=1
         socket="/var/run/mysqld/$1.sock"                                   while true
         cat $1.savepos | {                                                 do
           read host                                                           stop_and_save mysqld.$cnt
           read port                                                           cnt=`expr $cnt % 5 + 1`
           read file                                                           restore_and_start mysqld.$cnt
           read pos                                                            sleep 60
           change_master $socket                                           done
              $host $port $file $pos
           start_slave $socket
         }
       }




32   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Crash-safe Slaves
       Keeping replication information in sync with data
                                                                                     FILE               TABLE
        ●      Traditional Replication
                  –      Position stored in file
                  –      Update after transaction
                  –      Crash can lose update
        ●      Transactional Replication                                    ●   Repository location FILE or TABLE
                  –      Positions stored in table                                 master_info_repository
                  –      Update part of transaction                                relay_log_info_repository
                  –      Crash-safe

33   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Crash-safe Slaves
       Steps to set up crash-safe slaves

        ●      Direct server to use table-based repository
                  –      Defaults to FILE
                             master_info_repository=TABLE
                             relay_log_info_repository=TABLE
        ●      Ensure that a transactional engine is used
                  –      InnoDB default since 5.6.6
                  –      Before 5.6.6: set the storage engine
                             ALTER TABLE slave_master_info ENGINE = InnoDB
                             ALTER TABLE slave_relay_log_info ENGINE = InnoDB

34   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Round-Robin Replication
       A version using pure SQL

       CREATE TABLE my_masters (                                            CREATE TABLE current_master (
           idx INT PRIMARY KEY,                                                 idx INT
           host CHAR(50) NOT NULL,                                          ) ENGINE=InnoDB
           port INT NOT NULL DEFAULT 3306,
           log_file CHAR(50),
           log_pos LONG,
           UNIQUE INDEX (host,port,user)
       ) ENGINE=InnoDB

       CREATE PROCEDURE save_position()
       BEGIN
          DECLARE l_idx INT UNSIGNED;

          UPDATE my_masters AS mi, mysql.slave_relay_log_info AS rli
             SET mi.log_pos = rli.master_log_pos, mi.log_file = rli.master_log_name
           WHERE idx = (SELECT idx FROM current_master);
       END


35   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Round-Robin Replication
       In pure SQL


        CREATE PROCEDURE fetch_next_master(OUT p_host CHAR(50), OUT p_port INT UNSIGNED,
                                           OUT p_file CHAR(50), OUT p_pos BIGINT)
        BEGIN
           DECLARE l_next_idx INT DEFAULT 1;

               SELECT idx INTO l_next_idx FROM my_masters                     Select next index,
                WHERE idx > (SELECT idx FROM current_master)                  if there is one
                ORDER BY idx LIMIT 1;

               SELECT idx INTO l_next_idx FROM my_masters                      Select the first index, if
                WHERE idx >= l_next_idx ORDER BY idx LIMIT 1;
                                                                               there were no next index
               UPDATE current_master SET idx = l_next_idx;

           SELECT host, port, log_file, log_pos                             Fetch master info using
             INTO p_host, p_port, p_file, p_pos
             FROM my_masters WHERE idx = l_next_idx;                        the index
        END
36   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Round-Robin Replication
       In pure SQL


        CREATE EVENT multi_source ON SCHEDULE EVERY 10 SECOND DO
        BEGIN
           DECLARE l_host CHAR(50);
           DECLARE l_port INT UNSIGNED;
           DECLARE l_file CHAR(50);
           DECLARE l_pos BIGINT;

               SET SQL_LOG_BIN = 0;

           STOP SLAVE;
           START TRANSACTION;
           CALL save_current_position();
           CALL fetch_next_master(l_host, l_port, l_file, l_pos);
           CALL change_master(l_host, l_port, 'repl_user', 'xyzzy', l_file, l_pos);
           COMMIT;
           START SLAVE;
        END

37   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave


       ●      Upgrading
                 –      Example: Upgrading a topology without downtime
       ●      Saving space
                 –      Not keeping big columns on slave
       ●      Hiding data
                 –      Keeping data away from users
                 –      Note: still available in binary log and relay log – just not applied to table
       ●      Debugging and Auditing
                 –      Adding data for auditing

38   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave
       More columns on slave

       CREATE TABLE employee (
         name CHAR(40),
                                                                            Master   CREATE TABLE employee (
                                                                                       name CHAR(40),
                                                                                                                    Slave
         email CHAR(40)                                                                email CHAR(40),
                                                                                       changed TIMESTAMP
                                                                                          DEFAULT CURRENT_TIMESTAMP
                                                                                          ON UPDATE CURRENT_TIMESTAMP
       )                                                                             )

        ●      Same initial columns
        ●      Statement-based or row-based replication



39   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave
       More columns on master

       CREATE TABLE employee (                                              CREATE TABLE employee (
         name CHAR(40),                                                       name CHAR(40),
         email CHAR(40),                                                      email CHAR(40),
         password CHAR(40)                                                    password CHAR(40)
       )                     Master                                         )                       Slave

        ●      Same initial columns
        ●      Row-based replication only



40   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave
       Different types of columns on master and slave

       CREATE TABLE employee (                                              CREATE TABLE employee (
         emp_id INT,                                                          emp_id TINYINT,
         name CHAR(40),                                                       name CHAR(40),
         email CHAR(40)                                                       email CHAR(40)
       )                     Master                                         )                       Slave

        ●      Table definitions are identical
                         … except that some column type are different




41   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave
       Slave type conversions

       CREATE TABLE employee (                                              CREATE TABLE employee (
         emp_id INT,                                                          emp_id TINYINT,
         name CHAR(40),                                                       name CHAR(40),
         email CHAR(40)                                                       email CHAR(40)
       )                     Master                                         )                       Slave

        ●      Consider this statement:                      St
                                                               at
                                                                 em
                     INSERT INTO employee VALUES               Re ent
            Works fine (1, 'Bob', 'bob@example.com'),            pl     -b
                                                                   ica     a
                           (500, 'Alice', 'alice@example.com')        tio sed
             Fails silently!
                                                                         n


42   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave                                                     Before
                                                                                               MySQL 5.5.3
          Slave type conversions

          CREATE TABLE employee (                                              CREATE TABLE employee (
            emp_id TINYINT,                                                      emp_id INT,
            name CHAR(40),                                                       name CHAR(40),
            email CHAR(40)                                                       email CHAR(40)
          )                     Master                                         )                       Slave

           ●      Consider this statement:                      Ro
                                                                   w
                                                               Re -ba
                                                                 pl
                                                                   ica sed
                          INSERT INTO employee VALUES
                              (1, 'Bob', 'bob@example.com'),          tio
     Throws an         error!
                              (100, 'Alice', 'alice@example.com')         n



43      Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave                                                     MySQL 5.5.3
                                                                                                and later
       Slave type conversions

        ●      @@GLOBAL.SLAVE_TYPE_CONVERSIONS
                  –      Type: SET('ALL_LOSSY', 'ALL_NON_LOSSY')
                  –      Require slave restart


        ●      Lossy conversions                                            ●   Non-lossy conversions
                  –      INT → TINYINT                                          –   TINYINT → INT
                  –      CHAR(64) → VARCHAR(32)                                 –   VARCHAR(32) → CHAR(64)
                  –      DOUBLE → FLOAT                                         –   FLOAT → DOUBLE

44   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave                                     MySQL 5.5.3
                                                                               and later
       Slave type conversions

        ●      Conversions within same domain possible
                  –      INT, TINYINT, SMALLINT, MEDIUMINT, BIGINT
                  –      CHAR(n), VARCHAR(n), TINYTEXT, TEXT, …
                  –      DECIMAL(n,m), DOUBLE, FLOAT
        ●      ALL_NON_LOSSY in SLAVE_TYPE_CONVERSIONS
                  –      Conversion to larger domains allowed
        ●      ALL_LOSSY in SLAVE_TYPE_CONVERSIONS
                  –      Conversion to smaller domains allowed (truncation/rounding may occur)

45   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave                                                              MySQL 5.5.3
                                                                                                        and later
       Slave type conversions

       CREATE TABLE employee (                                                 CREATE TABLE employee (
         emp_id TINYINT,                                                         emp_id INT,
         name VARCHAR(40),                                                       name VARCHAR(40),
         email VARCHAR(40)                                                       email VARCHAR(40)
       )                     Master                                            )                       Slave

        ●      Consider this statement:                       Ro
                                                                 w
                                                             Re -ba
                                                               pl
                                                                 ica sed
                        INSERT INTO employee VALUES
                            (1, 'Bob', 'bob@example.com'),          tio
         Works        fine!
                            (100, 'Alice', 'alice@example.com')         n

                                                            SLAVE_TYPE_CONVERSIONS = 'ALL_NON_LOSSY'

46   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Different Tables on Master and Slave                                                              MySQL 5.5.3
                                                                                                           and later
          Slave type conversions

          CREATE TABLE employee (                                                 CREATE TABLE employee (
            emp_id INT,                                                             emp_id TINYINT,
            name VARCHAR(40),                                                       name VARCHAR(40),
            email VARCHAR(40)                                                       email VARCHAR(40)
          )                     Master                                            )                       Slave

           ●      Consider this statement:                      Ro
                                                                   w
                                                               Re -ba
                                                                 pl
                                                                   ica sed
                          INSERT INTO employee VALUES
                              (1, 'Bob', 'bob@example.com'),          tio
     Throws an         error!
                              (100, 'Alice', 'alice@example.com')         n

                                                               SLAVE_TYPE_CONVERSIONS = 'ALL_NON_LOSSY'

47      Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Master and Slave out of sync


        ●      Slave stopped with a strange error
                         ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY'
        ●      Compare two databases using mysqldbcompare
                         mysqldbcompare
                             --server1=root@master.example.com
                             --server2=root@slave1.example.com
                             employee




48   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Master and Slave out of sync
       Comparing two databases and finding the differences

       $ mysqldbcompare --quiet --server1=root@localhost:3309 --server2=root@localhost:3310 world
       # Checking databases world on server1 and world on server2
       #

       #
       # Data differences found among rows:
       --- world.City
       +++ world.City
       @@ -1,5 +1,5 @@
       -+-------+------------+--------------+-----------+-------------+
       -| ID    | Name       | CountryCode | District | Population |
       -+-------+------------+--------------+-----------+-------------+
       -| 3048 | Stockholm | SWE             | Lisboa   | 750348       |
       -+-------+------------+--------------+-----------+-------------+
       ++-------+-----------+--------------+-----------+-------------+
       +| ID    | Name      | CountryCode | District | Population |
       ++-------+-----------+--------------+-----------+-------------+
       +| 3048 | Helsinki | SWE             | Lisboa   | 750348      |
       ++-------+-----------+--------------+-----------+-------------+


49   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Master and Slave out of sync
       Synchronizing master and slave databases

       $   mysqldbcompare --quiet --difftype=sql --changes-for=server2 
       >   --server1=root@master.example.com --server2=root@slave1.example.com 
       >   world
       #   Checking databases world on server1 and world on server2
       #

       #
       # Transformation for --changes-for=server2:
       #

       # Data differences found among rows:
       UPDATE world.City SET Name = 'Stockholm' WHERE ID = '3048';




50   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Master and Slave out of sync
       Synchronizing master and slave databases

       $   mysqldbcompare --quiet --difftype=sql --changes-for=server1 
       >   --server1=root@master.example.com --server2=root@slave1.example.com 
       >   world
       #   Checking databases world on server1 and world on server2
       #

       #
       # Transformation for --changes-for=server1:
       #

       # Data differences found among rows:
       UPDATE world.City SET Name = 'Helsinki' WHERE ID = '3048';




51   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Replication Event Checksums
                                          Master                                        Slave




                                                                              Event
                                                                            Checksums



52   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Replication Event Checksums
       Configurations and options

        ●      Controlling checksum generation (default is CRC32 since 5.6.6)
                         SET GLOBAL BINLOG_CHECKSUM = CRC32
        ●      Enable verification on events read by dump thread
                         SET GLOBAL MASTER_VERIFY_CHECKSUM = ON
        ●      Enable verification on events read by SQL thread
                         SET GLOBAL SLAVE_SQL_VERIFY_CHECKSUM = ON




53   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
The preceding is intended to outline our general product direction. It is
     intended for information purposes only, and may not be incorporated
     into any contract. It is not a commitment to deliver any material, code,
     or functionality, and should not be relied upon in making purchasing
     decisions. The development, release, and timing of any features or
     functionality described for Oracle’s products remains at the sole
     discretion of Oracle.




54   Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

More Related Content

What's hot

5050 dev nation
5050 dev nation5050 dev nation
5050 dev nationArun Gupta
 
MySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellMySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellEmily Ikuta
 
OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09
OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09
OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09OSSCube
 
Parallel Query on Exadata
Parallel Query on ExadataParallel Query on Exadata
Parallel Query on ExadataEnkitec
 
New awesome features in MySQL 5.7
New awesome features in MySQL 5.7New awesome features in MySQL 5.7
New awesome features in MySQL 5.7Zhaoyang Wang
 
REST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using RESTREST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using RESTChristian Gohmann
 
2012 summarytables
2012 summarytables2012 summarytables
2012 summarytablessqlhjalp
 
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...Dave Stokes
 
[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama
[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama
[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke KajiyamaInsight Technology, Inc.
 
MythBusters Globalization Support - Avoid Data Corruption
MythBusters Globalization Support - Avoid Data CorruptionMythBusters Globalization Support - Avoid Data Corruption
MythBusters Globalization Support - Avoid Data CorruptionChristian Gohmann
 
Configuration beyond Java EE 8
Configuration beyond Java EE 8Configuration beyond Java EE 8
Configuration beyond Java EE 8Anatole Tresch
 
What’s New in Oracle Database 12c for PHP
What’s New in Oracle Database 12c for PHPWhat’s New in Oracle Database 12c for PHP
What’s New in Oracle Database 12c for PHPChristopher Jones
 
Mysql tech day_paris_ps_and_sys
Mysql tech day_paris_ps_and_sysMysql tech day_paris_ps_and_sys
Mysql tech day_paris_ps_and_sysMark Leith
 
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 Geir Høydalsvik
 
Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo...
 Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo... Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo...
Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo...Enkitec
 
PNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing DifficultPNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing DifficultDave Stokes
 
Drilling Deep Into Exadata Performance
Drilling Deep Into Exadata PerformanceDrilling Deep Into Exadata Performance
Drilling Deep Into Exadata PerformanceEnkitec
 
MySQL Enterprise Backup - BnR Scenarios
MySQL Enterprise Backup - BnR ScenariosMySQL Enterprise Backup - BnR Scenarios
MySQL Enterprise Backup - BnR ScenariosKeith Hollman
 

What's hot (20)

MySQL Monitoring 101
MySQL Monitoring 101MySQL Monitoring 101
MySQL Monitoring 101
 
5050 dev nation
5050 dev nation5050 dev nation
5050 dev nation
 
MySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellMySQL 5.7 in a Nutshell
MySQL 5.7 in a Nutshell
 
OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09
OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09
OSSCube MySQL Cluster Tutorial By Sonali At Osspac 09
 
Parallel Query on Exadata
Parallel Query on ExadataParallel Query on Exadata
Parallel Query on Exadata
 
New awesome features in MySQL 5.7
New awesome features in MySQL 5.7New awesome features in MySQL 5.7
New awesome features in MySQL 5.7
 
REST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using RESTREST in Piece - Administration of an Oracle Cluster/Database using REST
REST in Piece - Administration of an Oracle Cluster/Database using REST
 
2012 summarytables
2012 summarytables2012 summarytables
2012 summarytables
 
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
MySQL 5.7 NEW FEATURES, BETTER PERFORMANCE, AND THINGS THAT WILL BREAK -- Mid...
 
[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama
[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama
[B34] MySQL最新ロードマップ – MySQL 5.7とその先へ by Ryusuke Kajiyama
 
MythBusters Globalization Support - Avoid Data Corruption
MythBusters Globalization Support - Avoid Data CorruptionMythBusters Globalization Support - Avoid Data Corruption
MythBusters Globalization Support - Avoid Data Corruption
 
Configuration beyond Java EE 8
Configuration beyond Java EE 8Configuration beyond Java EE 8
Configuration beyond Java EE 8
 
What’s New in Oracle Database 12c for PHP
What’s New in Oracle Database 12c for PHPWhat’s New in Oracle Database 12c for PHP
What’s New in Oracle Database 12c for PHP
 
Mysql tech day_paris_ps_and_sys
Mysql tech day_paris_ps_and_sysMysql tech day_paris_ps_and_sys
Mysql tech day_paris_ps_and_sys
 
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
 
Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo...
 Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo... Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo...
Tuning SQL for Oracle Exadata: The Good, The Bad, and The Ugly Tuning SQL fo...
 
PNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing DifficultPNWPHP -- What are Databases so &#%-ing Difficult
PNWPHP -- What are Databases so &#%-ing Difficult
 
Less18 support
Less18 supportLess18 support
Less18 support
 
Drilling Deep Into Exadata Performance
Drilling Deep Into Exadata PerformanceDrilling Deep Into Exadata Performance
Drilling Deep Into Exadata Performance
 
MySQL Enterprise Backup - BnR Scenarios
MySQL Enterprise Backup - BnR ScenariosMySQL Enterprise Backup - BnR Scenarios
MySQL Enterprise Backup - BnR Scenarios
 

Similar to Replication Tips & Trick for SMUG

Replication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party ExtinctionReplication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party ExtinctionBen Mildren
 
Oracle OpenWorld 2013 - HOL9737 MySQL Replication Best Practices
Oracle OpenWorld 2013 - HOL9737 MySQL Replication Best PracticesOracle OpenWorld 2013 - HOL9737 MySQL Replication Best Practices
Oracle OpenWorld 2013 - HOL9737 MySQL Replication Best PracticesSven Sandberg
 
MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) Frazer Clement
 
My sql replication advanced techniques presentation
My sql replication advanced techniques presentationMy sql replication advanced techniques presentation
My sql replication advanced techniques presentationepee
 
Performance Schema and Sys Schema in MySQL 5.7
Performance Schema and Sys Schema in MySQL 5.7Performance Schema and Sys Schema in MySQL 5.7
Performance Schema and Sys Schema in MySQL 5.7Mark Leith
 
OSI_MySQL_Performance Schema
OSI_MySQL_Performance SchemaOSI_MySQL_Performance Schema
OSI_MySQL_Performance SchemaMayank Prasad
 
MySQL Replication Update -- Zendcon 2016
MySQL Replication Update -- Zendcon 2016MySQL Replication Update -- Zendcon 2016
MySQL Replication Update -- Zendcon 2016Dave Stokes
 
Advanced MySQL Replication Architectures - Luis Soares
Advanced MySQL Replication Architectures - Luis SoaresAdvanced MySQL Replication Architectures - Luis Soares
Advanced MySQL Replication Architectures - Luis SoaresMySQL Brasil
 
2 ivan ma-mysql複製的演進和應用-twn- v1
2 ivan ma-mysql複製的演進和應用-twn- v12 ivan ma-mysql複製的演進和應用-twn- v1
2 ivan ma-mysql複製的演進和應用-twn- v1Ivan Tu
 
lock, block & two smoking barrels
lock, block & two smoking barrelslock, block & two smoking barrels
lock, block & two smoking barrelsMark Broadbent
 
PostgreSQL replication
PostgreSQL replicationPostgreSQL replication
PostgreSQL replicationMasao Fujii
 
Fosdem2012 mariadb-5.3-query-optimizer-r2
Fosdem2012 mariadb-5.3-query-optimizer-r2Fosdem2012 mariadb-5.3-query-optimizer-r2
Fosdem2012 mariadb-5.3-query-optimizer-r2Sergey Petrunya
 
MySQL 5.7 -- SCaLE Feb 2014
MySQL 5.7 -- SCaLE Feb 2014MySQL 5.7 -- SCaLE Feb 2014
MySQL 5.7 -- SCaLE Feb 2014Dave Stokes
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Boris Hristov
 
MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016Dave Stokes
 
Consolidated shared indexes in real time
Consolidated shared indexes in real timeConsolidated shared indexes in real time
Consolidated shared indexes in real timeJeff Mace
 

Similar to Replication Tips & Trick for SMUG (20)

Replication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party ExtinctionReplication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party Extinction
 
Oracle OpenWorld 2013 - HOL9737 MySQL Replication Best Practices
Oracle OpenWorld 2013 - HOL9737 MySQL Replication Best PracticesOracle OpenWorld 2013 - HOL9737 MySQL Replication Best Practices
Oracle OpenWorld 2013 - HOL9737 MySQL Replication Best Practices
 
MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014)
 
My sql replication advanced techniques presentation
My sql replication advanced techniques presentationMy sql replication advanced techniques presentation
My sql replication advanced techniques presentation
 
Performance Schema and Sys Schema in MySQL 5.7
Performance Schema and Sys Schema in MySQL 5.7Performance Schema and Sys Schema in MySQL 5.7
Performance Schema and Sys Schema in MySQL 5.7
 
OSI_MySQL_Performance Schema
OSI_MySQL_Performance SchemaOSI_MySQL_Performance Schema
OSI_MySQL_Performance Schema
 
MySQL Replication
MySQL ReplicationMySQL Replication
MySQL Replication
 
MySQL Replication Update -- Zendcon 2016
MySQL Replication Update -- Zendcon 2016MySQL Replication Update -- Zendcon 2016
MySQL Replication Update -- Zendcon 2016
 
Advanced MySQL Replication Architectures - Luis Soares
Advanced MySQL Replication Architectures - Luis SoaresAdvanced MySQL Replication Architectures - Luis Soares
Advanced MySQL Replication Architectures - Luis Soares
 
PostgreSQL replication
PostgreSQL replicationPostgreSQL replication
PostgreSQL replication
 
2 ivan ma-mysql複製的演進和應用-twn- v1
2 ivan ma-mysql複製的演進和應用-twn- v12 ivan ma-mysql複製的演進和應用-twn- v1
2 ivan ma-mysql複製的演進和應用-twn- v1
 
lock, block & two smoking barrels
lock, block & two smoking barrelslock, block & two smoking barrels
lock, block & two smoking barrels
 
PostgreSQL replication
PostgreSQL replicationPostgreSQL replication
PostgreSQL replication
 
plsql les06
 plsql les06 plsql les06
plsql les06
 
MySQL NoSQL APIs
MySQL NoSQL APIsMySQL NoSQL APIs
MySQL NoSQL APIs
 
Fosdem2012 mariadb-5.3-query-optimizer-r2
Fosdem2012 mariadb-5.3-query-optimizer-r2Fosdem2012 mariadb-5.3-query-optimizer-r2
Fosdem2012 mariadb-5.3-query-optimizer-r2
 
MySQL 5.7 -- SCaLE Feb 2014
MySQL 5.7 -- SCaLE Feb 2014MySQL 5.7 -- SCaLE Feb 2014
MySQL 5.7 -- SCaLE Feb 2014
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
 
MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016MySQL Replication Overview -- PHPTek 2016
MySQL Replication Overview -- PHPTek 2016
 
Consolidated shared indexes in real time
Consolidated shared indexes in real timeConsolidated shared indexes in real time
Consolidated shared indexes in real time
 

More from Mats Kindahl

Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricMats Kindahl
 
High-Availability using MySQL Fabric
High-Availability using MySQL FabricHigh-Availability using MySQL Fabric
High-Availability using MySQL FabricMats Kindahl
 
Elastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStackElastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStackMats Kindahl
 
Sharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL FabricSharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL FabricMats Kindahl
 
MySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL ServersMySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL ServersMats Kindahl
 
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFSMySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFSMats Kindahl
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMats Kindahl
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesMats Kindahl
 
Mysteries of the binary log
Mysteries of the binary logMysteries of the binary log
Mysteries of the binary logMats Kindahl
 

More from Mats Kindahl (10)

Why rust?
Why rust?Why rust?
Why rust?
 
Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL Fabric
 
High-Availability using MySQL Fabric
High-Availability using MySQL FabricHigh-Availability using MySQL Fabric
High-Availability using MySQL Fabric
 
Elastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStackElastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStack
 
Sharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL FabricSharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL Fabric
 
MySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL ServersMySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL Servers
 
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFSMySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL Databases
 
Mysteries of the binary log
Mysteries of the binary logMysteries of the binary log
Mysteries of the binary log
 

Recently uploaded

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Recently uploaded (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Replication Tips & Trick for SMUG

  • 1. Replication Tips & Tricks + some things about GTIDs Mats Kindahl mats.kindahl@oracle.com 1Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 12
  • 2. Program Agenda  Replication setup and status checking  Slave fail-over using GTID  Binary log analysis  Crash-safe slaves  Multi-source replication 2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 3. About the Presentation This presentation will introduce you to some replication features and also briefly show tips and tricks on how to work with replication. The focus is on short ideas and each item does not go deeper into details. 3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 4. What is Replication? ● MySQL Master Server – Changes data – Sends changes to slave ● MySQL Slave Server – Receives changes from master – Applies received changes to database 4 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 5. Replication Topologies Dual Master Circular Tree Simple 5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 6. Why Replication? Scaling out Writes Reads 6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 7. Why Replication? Redundancy Slave Crash Promotion New Master 7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 8. Replication Architecture Master Slave 8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 9. Reading Slave Status Understanding the fields of SHOW SLAVE STATUS ● I/O Thread Status ● SQL Thread Status – Slave_IO_Running – Slave_SQL_Running – Last_IO_Errno – Last_SQL_Errno – Last_IO_Error – Last_SQL_Error – Last_IO_Error_Timestamp – Last_SQL_Error_Timestamp ● Master being replicated from – Master_Host – Master_Port 9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 10. Reading Slave Status Understanding the fields of SHOW SLAVE STATUS ● Next event to execute – in master log coordinates – Relay_Master_Log_File + Exec_Master_Log_Pos ● Next event to execute – in relay log coordinates Relay_Log_File + Relay_Log_Pos ● Next event to read from master Master_Log_File + Read_Master_Log_Pos 10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 11. Reading the Binary Log Decoding the binary log ● Use mysqlbinlog --hexdump Show hex dump of event as comment --start-position Start dumping at a position --stop-position Stop dumping after this position # at 275 175 =373 16 10 #120927 23:11:58 server id 3 end_log_pos 373 # Position Timestamp Type Master ID Size Master Pos Flags # 113 1e c1 64 50 02 03 00 00 00 62 00 00 00 75 01 00 00 00 00 Little-endian Query 11 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 12. Reading the Binary Log Decoding the binary log # at 275 #120927 23:11:58 server id 3 end_log_pos 373 # Position Timestamp Type Master ID Size Master Pos Flags # 113 1e c1 64 50 02 03 00 00 00 62 00 00 00 75 01 00 00 00 00 # 126 c5 03 00 00 00 00 00 00 04 00 00 1a 00 00 00 00 |................| # 136 00 00 01 00 00 00 00 00 00 00 00 06 03 73 74 64 |.............std| # 146 04 21 00 21 00 08 00 74 65 73 74 00 69 6e 73 65 |.......test.inse| # 156 72 74 20 69 6e 74 6f 20 74 32 20 76 61 6c 75 65 |rt.into.t2.value| # 166 73 20 28 31 2c 27 74 65 73 74 69 6e 67 27 29 |s..1..testing..| # Query thread_id=965 exec_time=0 error_code=0 SET TIMESTAMP=1348780318/*!*/; insert into t2 values (1,'testing') /*!*/; 12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 13. Reading the Binary Log Decode row events ● Use mysqlbinlog --verbose Decode row events into pseudo-SQL # at 849 # at 893 #120928 15:19:24 server id 3 end_log_pos 893 Table_map: `test`.`t2` mapped to number 48 #120928 15:19:24 server id 3 end_log_pos 941 Write_rows: table id 48 flags: STMT_END_F BINLOG ' 3KNlUBMDAAAALAAAAH0DAAAAADAAAAAAAAEABHRlc3QAAnQyAAIDDwIoAAM= 3KNlUBcDAAAAMAAAAK0DAAAAADAAAAAAAAEAAv/8AwAAAA1yb3dzIGFyZSBjb29s '/*!*/; 13 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 14. Reading the Binary Log Decode row events ● Use mysqlbinlog --verbose Decode row events into pseudo-SQL # at 849 # at 893 #120928 15:19:24 server id 3 end_log_pos 893 Table_map: `test`.`t2` mapped to number 48 #120928 15:19:24 server id 3 end_log_pos 941 Write_rows: table id 48 flags: STMT_END_F BINLOG ' 3KNlUBMDAAAALAAAAH0DAAAAADAAAAAAAAEABHRlc3QAAnQyAAIDDwIoAAM= 3KNlUBcDAAAAMAAAAK0DAAAAADAAAAAAAAEAAv/8AwAAAA1yb3dzIGFyZSBjb29s '/*!*/; ### INSERT INTO test.t2 ### SET ### @1=3 ### @2='rows are cool' 14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 15. Global Transaction Identifiers (GTIDs) Handling positions in MySQL 5.5 ● Binary log positions manually handled ● Each server has it's own position ● Failing over slaves to new masters difficult – What is the position to fail over to? CHANGE MASTER TO MASTER_HOST='master1.example.com', MASTER_PORT=3306, MASTER_USER='repl_user', MASTER_PASSWORD='xyzzy', MASTER_LOG_FILE='master-bin.00001', MASTER_LOG_POS=22145; Different for different servers 15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 16. Global Transaction Identifiers (GTIDs) Enabling Global Transaction IDs ● MySQL 5.6 has Global Transaction ID – Positions independent of server ● GTID handshake – Done on connection with master – Negotiate position automatically CHANGE MASTER TO MASTER_HOST='master1.example.com', MASTER_PORT=3306, MASTER_USER='repl_user', MASTER_PASSWORD='xyzzy', MASTER_LOG_FILE='master-bin.00001', MASTER_LOG_POS=22145; MASTER_AUTO_POSITION=1; 16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 17. Global Transaction Identifiers (GTIDs) Enabling Global Transaction IDs ● Turn on GTIDs [mysqld] … ● Turn off dangerous statements gtid-mode=on – CREATE TABLE...SELECT enforce­gtid­consistency=on log-bin=master-bin – CREATE TEMPORARY TABLE log-slave-updates ● Inside transactions CHANGE MASTER TO MASTER_HOST='master1.example.com', MASTER_PORT=3306, MASTER_USER='repl_user', MASTER_PASSWORD='xyzzy', MASTER_LOG_FILE='master-bin.00001', MASTER_LOG_POS=22145; MASTER_AUTO_POSITION=1; 17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 18. Global Transaction Identifiers (GTIDs) Global Transaction ID Concepts ● Global transaction ID – A server UUID + Transaction Number a61678ba­4889­4279­9e58­45ba840af334:1 – Preserved when replicated ● Global Transaction ID Set – Sequence of Server UUID + Transaction Number Range a61678ba­4889­4279­9e58­45ba840af334:1­5, f88e2a43­a13e­11e2­98de­0021cc6850ca:12­2564 18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 19. Global Transaction Identifiers (GTIDs) Server Variables ● @@GTID_EXECUTED – GTID set of all transactions logged in the binary log ● @@GTID_PURGED – GTID set of all transaction purged from binary log – Cannot be sent to slaves 19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 20. Cloning a Slave Be My fo Creating a slave image SQ re L 5. 1. Stop the slave 6 2. Write down where slave has stopped – SHOW SLAVE STATUS – Relay_Master_Log_File + Exec_Master_Log_Pos 3. Backup slave – mysqldump – slow but safe ­­dump­slave Generate CHANGE MASTER – Physical file copy – fast but you need to shut down the server 20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 21. Cloning a Slave Be My fo Setting up the new slave SQ re L 5. 4. Restore backup on new slave 6 5. Direct the slave to the master – CHANGE MASTER – Master_Host + Master_Port – Relay_Master_Log_File + Exec_Master_Log_Pos 6. Start slave – START SLAVE 21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 22. Cloning a Slave My SQ or L 5 1. Stop the slave lat .6 er 2. Backup slave mysqldump ­­host=slave1.example.com ­­user=root     ­­dump­slave ­­set­gtid­purged >image.sql 3. Start the slave Tell slave that transactions 4. Restore image on new slave in image cannot be replicated mysql ­­host=slave2.example.com ­­user=root <image.sql 5. Start Slave 22 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 23. Point in time recovery ● Use mysqlbinlog --to-datetime Stop reading when reaching date ● Example mysqlbinlog --read-from-remote-server e --host=master -uroot --position=192 ar ! --to-datetime=”2009-04-11 12:36:56” ps ing am reas st master-bin.00002[2-4] | e nc mysql -uroot --host=slave tim lly i : a ing ic r n ot on W a on m not 23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 24. Using Relay Servers ● Relieve master server by creating relay slaves ● Just keep binary logs ● Do not store data in tables – Use BLACKHOLE engine – --log-slave-updates SET STORAGE_ENGINE = BLACKHOLE ALTER TABLE table ENGINE = BLACKHOLE 24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 25. Using Relay Servers replicate-wild-do-table=*.%_east replicate-wild-do-table=*.%_west ● Filtering replication stream ● Filtering done on relay servers ● replicate­wild­*­table – Work with cross-database queries 25 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 26. Write Your Own Library Write your own utility library ● Create a utility library to easier work with replication ● Common functions to manage replication: – Start/stop slave – Change master – Fetch master position – Fetch slave execute/read position – Fetch master host information 26 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 27. Write Your Own Library Basic functions using Bourne shell # Usage: mysql_exec socket sql ...  # Usage: stop_slave socket [ thread ] mysql_exec () { stop_slave () {     sock=$1    mysql_exec $1 STOP SLAVE $2     shift 1 }     mysql ­uroot ­­vertical ­­batch          ­­skip­column­names          # Usage: start_slave socket [ thread ]         ­­socket="$sock"             start_slave () {         ­­exec "$*"    mysql_exec $1 START SLAVE $2 } } 27 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 28. Write Your Own Library Basic functions using Bourne shell # Usage: change_master socket [ host [ port [ file [ pos ] ] ] ] change_master () {     host=${2:+MASTER_HOST='$2'}     port=${3:+,MASTER_PORT=$3}     file=${4:+,MASTER_LOG_FILE='$4'}     pos=${5:+,MASTER_LOG_POS=$5}     mysql_exec $1 CHANGE MASTER TO $host $port $file $pos } # Usage: fetch_master_pos socket fetch_master_pos () {    mysql_exec $1 SHOW MASTER STATUS |    grep '<File|<Pos'             |    cut ­f2 ­d: } 28 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 29. Write Your Own Library Basic functions using Bourne shell # Usage: fetch_slave_exec_pos socket fetch_slave_exec_pos () {    mysql_exec $1 SHOW SLAVE STATUS |    grep '<Relay_Master_Log_File|<Exec_Master_Log_Pos' |    cut ­f2 ­d: } # Usage: fetch_slave_read_pos socket fetch_slave_read_pos () {    mysql_exec $1 SHOW SLAVE STATUS |    grep '<Master_Log_File|<Read_Master_Log_Pos' |    cut ­f2 ­d: } 29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 30. master1.example.com master2.example.com Round-Robin Replication ● Slave can only replicate from single master at a time ● Use time sharing to replicate from several masters Stop Switcher Start Save slave1.example.com Restore 30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 31. Round-Robin Replication A version using Bourne Shell # Usage: fetch_host_and_pos socket fetch_host_and_pos () { mysql_exec $1 SHOW SLAVE STATUS | grep '<Master_(Host|Port|Log_File)|<Read_Master_Log_Pos' | cut -f2 -d: } # Usage: stop_and_save socket stop_and_save () { sock="/var/run/mysqld/$1.sock" stop_slave $socket fetch_host_and_pos $sock >$1.savepos } 31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 32. Round-Robin Replication A version using Bourne Shell restore_and_start () { cnt=1 socket="/var/run/mysqld/$1.sock" while true cat $1.savepos | { do read host stop_and_save mysqld.$cnt read port cnt=`expr $cnt % 5 + 1` read file restore_and_start mysqld.$cnt read pos sleep 60 change_master $socket done $host $port $file $pos start_slave $socket } } 32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 33. Crash-safe Slaves Keeping replication information in sync with data FILE TABLE ● Traditional Replication – Position stored in file – Update after transaction – Crash can lose update ● Transactional Replication ● Repository location FILE or TABLE – Positions stored in table master_info_repository – Update part of transaction relay_log_info_repository – Crash-safe 33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 34. Crash-safe Slaves Steps to set up crash-safe slaves ● Direct server to use table-based repository – Defaults to FILE master_info_repository=TABLE relay_log_info_repository=TABLE ● Ensure that a transactional engine is used – InnoDB default since 5.6.6 – Before 5.6.6: set the storage engine ALTER TABLE slave_master_info ENGINE = InnoDB ALTER TABLE slave_relay_log_info ENGINE = InnoDB 34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 35. Round-Robin Replication A version using pure SQL CREATE TABLE my_masters ( CREATE TABLE current_master ( idx INT PRIMARY KEY, idx INT host CHAR(50) NOT NULL, ) ENGINE=InnoDB port INT NOT NULL DEFAULT 3306, log_file CHAR(50), log_pos LONG, UNIQUE INDEX (host,port,user) ) ENGINE=InnoDB CREATE PROCEDURE save_position() BEGIN DECLARE l_idx INT UNSIGNED; UPDATE my_masters AS mi, mysql.slave_relay_log_info AS rli SET mi.log_pos = rli.master_log_pos, mi.log_file = rli.master_log_name WHERE idx = (SELECT idx FROM current_master); END 35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 36. Round-Robin Replication In pure SQL CREATE PROCEDURE fetch_next_master(OUT p_host CHAR(50), OUT p_port INT UNSIGNED, OUT p_file CHAR(50), OUT p_pos BIGINT) BEGIN DECLARE l_next_idx INT DEFAULT 1; SELECT idx INTO l_next_idx FROM my_masters Select next index, WHERE idx > (SELECT idx FROM current_master) if there is one ORDER BY idx LIMIT 1; SELECT idx INTO l_next_idx FROM my_masters Select the first index, if WHERE idx >= l_next_idx ORDER BY idx LIMIT 1; there were no next index UPDATE current_master SET idx = l_next_idx; SELECT host, port, log_file, log_pos Fetch master info using INTO p_host, p_port, p_file, p_pos FROM my_masters WHERE idx = l_next_idx; the index END 36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 37. Round-Robin Replication In pure SQL CREATE EVENT multi_source ON SCHEDULE EVERY 10 SECOND DO BEGIN DECLARE l_host CHAR(50); DECLARE l_port INT UNSIGNED; DECLARE l_file CHAR(50); DECLARE l_pos BIGINT; SET SQL_LOG_BIN = 0; STOP SLAVE; START TRANSACTION; CALL save_current_position(); CALL fetch_next_master(l_host, l_port, l_file, l_pos); CALL change_master(l_host, l_port, 'repl_user', 'xyzzy', l_file, l_pos); COMMIT; START SLAVE; END 37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 38. Different Tables on Master and Slave ● Upgrading – Example: Upgrading a topology without downtime ● Saving space – Not keeping big columns on slave ● Hiding data – Keeping data away from users – Note: still available in binary log and relay log – just not applied to table ● Debugging and Auditing – Adding data for auditing 38 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 39. Different Tables on Master and Slave More columns on slave CREATE TABLE employee ( name CHAR(40), Master CREATE TABLE employee ( name CHAR(40), Slave email CHAR(40) email CHAR(40), changed TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ) ● Same initial columns ● Statement-based or row-based replication 39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 40. Different Tables on Master and Slave More columns on master CREATE TABLE employee ( CREATE TABLE employee ( name CHAR(40), name CHAR(40), email CHAR(40), email CHAR(40), password CHAR(40) password CHAR(40) ) Master ) Slave ● Same initial columns ● Row-based replication only 40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 41. Different Tables on Master and Slave Different types of columns on master and slave CREATE TABLE employee ( CREATE TABLE employee ( emp_id INT, emp_id TINYINT, name CHAR(40), name CHAR(40), email CHAR(40) email CHAR(40) ) Master ) Slave ● Table definitions are identical … except that some column type are different 41 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 42. Different Tables on Master and Slave Slave type conversions CREATE TABLE employee ( CREATE TABLE employee ( emp_id INT, emp_id TINYINT, name CHAR(40), name CHAR(40), email CHAR(40) email CHAR(40) ) Master ) Slave ● Consider this statement: St at em INSERT INTO employee VALUES Re ent Works fine (1, 'Bob', 'bob@example.com'), pl -b ica a (500, 'Alice', 'alice@example.com') tio sed Fails silently! n 42 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 43. Different Tables on Master and Slave Before MySQL 5.5.3 Slave type conversions CREATE TABLE employee ( CREATE TABLE employee ( emp_id TINYINT, emp_id INT, name CHAR(40), name CHAR(40), email CHAR(40) email CHAR(40) ) Master ) Slave ● Consider this statement: Ro w Re -ba pl ica sed INSERT INTO employee VALUES (1, 'Bob', 'bob@example.com'), tio Throws an error! (100, 'Alice', 'alice@example.com') n 43 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 44. Different Tables on Master and Slave MySQL 5.5.3 and later Slave type conversions ● @@GLOBAL.SLAVE_TYPE_CONVERSIONS – Type: SET('ALL_LOSSY', 'ALL_NON_LOSSY') – Require slave restart ● Lossy conversions ● Non-lossy conversions – INT → TINYINT – TINYINT → INT – CHAR(64) → VARCHAR(32) – VARCHAR(32) → CHAR(64) – DOUBLE → FLOAT  – FLOAT → DOUBLE 44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 45. Different Tables on Master and Slave MySQL 5.5.3 and later Slave type conversions ● Conversions within same domain possible – INT, TINYINT, SMALLINT, MEDIUMINT, BIGINT – CHAR(n), VARCHAR(n), TINYTEXT, TEXT, … – DECIMAL(n,m), DOUBLE, FLOAT ● ALL_NON_LOSSY in SLAVE_TYPE_CONVERSIONS – Conversion to larger domains allowed ● ALL_LOSSY in SLAVE_TYPE_CONVERSIONS – Conversion to smaller domains allowed (truncation/rounding may occur) 45 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 46. Different Tables on Master and Slave MySQL 5.5.3 and later Slave type conversions CREATE TABLE employee ( CREATE TABLE employee ( emp_id TINYINT, emp_id INT, name VARCHAR(40), name VARCHAR(40), email VARCHAR(40) email VARCHAR(40) ) Master ) Slave ● Consider this statement: Ro w Re -ba pl ica sed INSERT INTO employee VALUES (1, 'Bob', 'bob@example.com'), tio Works fine! (100, 'Alice', 'alice@example.com') n SLAVE_TYPE_CONVERSIONS = 'ALL_NON_LOSSY' 46 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 47. Different Tables on Master and Slave MySQL 5.5.3 and later Slave type conversions CREATE TABLE employee ( CREATE TABLE employee ( emp_id INT, emp_id TINYINT, name VARCHAR(40), name VARCHAR(40), email VARCHAR(40) email VARCHAR(40) ) Master ) Slave ● Consider this statement: Ro w Re -ba pl ica sed INSERT INTO employee VALUES (1, 'Bob', 'bob@example.com'), tio Throws an error! (100, 'Alice', 'alice@example.com') n SLAVE_TYPE_CONVERSIONS = 'ALL_NON_LOSSY' 47 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 48. Master and Slave out of sync ● Slave stopped with a strange error ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY' ● Compare two databases using mysqldbcompare mysqldbcompare --server1=root@master.example.com --server2=root@slave1.example.com employee 48 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 49. Master and Slave out of sync Comparing two databases and finding the differences $ mysqldbcompare --quiet --server1=root@localhost:3309 --server2=root@localhost:3310 world # Checking databases world on server1 and world on server2 # # # Data differences found among rows: --- world.City +++ world.City @@ -1,5 +1,5 @@ -+-------+------------+--------------+-----------+-------------+ -| ID | Name | CountryCode | District | Population | -+-------+------------+--------------+-----------+-------------+ -| 3048 | Stockholm | SWE | Lisboa | 750348 | -+-------+------------+--------------+-----------+-------------+ ++-------+-----------+--------------+-----------+-------------+ +| ID | Name | CountryCode | District | Population | ++-------+-----------+--------------+-----------+-------------+ +| 3048 | Helsinki | SWE | Lisboa | 750348 | ++-------+-----------+--------------+-----------+-------------+ 49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 50. Master and Slave out of sync Synchronizing master and slave databases $ mysqldbcompare --quiet --difftype=sql --changes-for=server2 > --server1=root@master.example.com --server2=root@slave1.example.com > world # Checking databases world on server1 and world on server2 # # # Transformation for --changes-for=server2: # # Data differences found among rows: UPDATE world.City SET Name = 'Stockholm' WHERE ID = '3048'; 50 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 51. Master and Slave out of sync Synchronizing master and slave databases $ mysqldbcompare --quiet --difftype=sql --changes-for=server1 > --server1=root@master.example.com --server2=root@slave1.example.com > world # Checking databases world on server1 and world on server2 # # # Transformation for --changes-for=server1: # # Data differences found among rows: UPDATE world.City SET Name = 'Helsinki' WHERE ID = '3048'; 51 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 52. Replication Event Checksums Master Slave Event Checksums 52 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 53. Replication Event Checksums Configurations and options ● Controlling checksum generation (default is CRC32 since 5.6.6) SET GLOBAL BINLOG_CHECKSUM = CRC32 ● Enable verification on events read by dump thread SET GLOBAL MASTER_VERIFY_CHECKSUM = ON ● Enable verification on events read by SQL thread SET GLOBAL SLAVE_SQL_VERIFY_CHECKSUM = ON 53 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 54. The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 54 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.