Mysql репликация пропустить ошибку

There is a system with ROW-based replication.
Yesterday i have executed a heavy statement on my master accidently and found my slaves far behind master. I have interrupted the query on master, but it was still running on slaves.
So i got my slaves 15 hours behind master.

I have already tried to step over one position by resetting slave and increasing MASTER_LOG_POS, but with no luck: position wasn’t found, because relay log wasn’t read further than a heavy query event.

Read_Master_Log_Pos == Exec_Master_Log_Pos
  • Is there any way to skip the heavy query?
    (i don’t care about data that has to be changed by query)
  • Is there a way to kill a query on a slave taken from relay log?
  • Is there a way to roll the slaves back in 1 position, remove the
    event from master bin-log and resume the replication?

asked Jul 17, 2013 at 13:47

Volodymyr Linevych's user avatar

Try the following on the slave:

STOP SLAVE;
SET GLOBAL sql_slave_skip_counter = 1;
START SLAVE;

This will stop the slaves threads and skips the next event from the master. This you normally use when you have problems with statements to skip over them.

Also read following part of the mysql docs: set-global-sql-slave-skip-counter

Christopher Schultz's user avatar

answered Jul 17, 2013 at 14:10

Flo Doe's user avatar

1

First explore the binary logs on the master to find the SQL statement that is causing the issue, using the following on the master:

SHOW BINLOG EVENTS IN 'mysql-bin.000XXX' LIMIT 100;

Then set the slave to only sync up to the statement before that:

STOP SLAVE;
START SLAVE UNTIL MASTER_LOG_FILE = 'log_name', MASTER_LOG_POS = log_pos;

When you want it to carry on replication after the bad statement (warning, this can be dangerous if the statement changed data) you can tell the slave to continue from a specific point in the masters log. To do this get the position using the first command on the master, then set the slave to go:

CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000663', MASTER_LOG_POS=4;
START SLAVE;

answered Jul 8, 2014 at 22:07

A.Badger's user avatar

A.BadgerA.Badger

4,2691 gold badge26 silver badges18 bronze badges

0

For those on Amazon RDS MySQL you can skip one error at a time on the slave with:

CALL mysql.rds_skip_repl_error;

No need to stop replication before running this.

answered Mar 18, 2016 at 18:38

Sean Fahey's user avatar

Sean FaheySean Fahey

1,8403 gold badges26 silver badges36 bronze badges

I found the starting the io_thread first

start slave io_thread;

and checking the relay logs with the command

SHOW RELAYLOG EVENTS IN 'mysql-bin.000XXX' LIMIT 100;

This saved me a lot of time.

answered Feb 8, 2017 at 18:00

Rodo's user avatar

RodoRodo

1,5681 gold badge14 silver badges11 bronze badges

You can set a skip counter as follow:

mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;
mysql> START SLAVE; 

To see the processlist:

mysql> show [full] processlist;
kill "number from first col";

Start slave from specific position:

START SLAVE UNTIL MASTER_LOG_FILE = 'log_name', MASTER_LOG_POS = log_pos

Ref: http://dev.mysql.com/doc/refman/5.0/en/start-slave.html

answered Jul 17, 2013 at 14:08

Teun Ouwehand's user avatar

mysql master-slave replication, often encounter errors and lead to slave end replication interruption, this time generally requires manual intervention, skip errors to continue

There are two ways to skip errors:

1.1 Skip a specified number of transactions:

mysql>stop slave;
mysql>SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1;        #Skip a transaction
mysql>start slave;

1.2 Modify mysql configuration file to skip all errors or specified types of errors through the slave_skip_errors parameter

vi /etc/my.cnf
[mysqld]
#slave-skip-errors=1062,1053,1146 #Skip the error of the specified error no type
#slave-skip-errors=all #Skip all errors

2 cases

Let’s simulate an error scenario
Environment (a configured master-slave replication environment)
master database IP: 192.168.247.128
Slve database IP: 192.168.247.130
mysql version: 5.6.14
binlog-do-db = mydb

Execute the following statement on master:

mysql>use mysql;
mysql>create table t1 (id int);
mysql>use mydb;
mysql>insert into mysql.t1 select 1;

View replication status on slave

mysql> show slave status G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.247.128
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000017
          Read_Master_Log_Pos: 2341
               Relay_Log_File: DBtest1-relay-bin.000011
                Relay_Log_Pos: 494
        Relay_Master_Log_File: mysql-bin.000017
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 1146
                   Last_Error: Error 'Table 'mysql.t1' doesn't exist' on query. Default database: 'mydb'. Query: 'insert into mysql.t1 select 1'
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 1919
              Relay_Log_Space: 1254
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 1146
               Last_SQL_Error: Error 'Table 'mysql.t1' doesn't exist' on query. Default database: 'mydb'. Query: 'insert into mysql.t1 select 1'
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: f0f7faf6-51a8-11e3-9759-000c29eed3ea
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: 
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 131210 21:37:19
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
1 row in set (0.00 sec)

As can be seen from the results, Read_Master_Log_Pos: 2341, Exec_Master_Log_Pos: 1919 error Last_SQL_Error: Error’Table’mysql.t1’does’t exist’ on query.
Because only binlog is recorded for mydb, errors occur when tables in other databases are operated on the mydb library but do not exist on slave.

Let’s look at the transaction content in the binlog, where a row represents a transaction.

mysql> SHOW BINLOG EVENTS in 'mysql-bin.000017' from 1919G
*************************** 1. row ***************************
   Log_name: mysql-bin.000017
        Pos: 1919
 Event_type: Query
  Server_id: 1
End_log_pos: 1999
       Info: BEGIN
*************************** 2. row ***************************
   Log_name: mysql-bin.000017
        Pos: 1999
 Event_type: Query
  Server_id: 1
End_log_pos: 2103
       Info: use `mydb`; insert into mysql.t1 select 1
*************************** 3. row ***************************
   Log_name: mysql-bin.000017
        Pos: 2103
 Event_type: Xid
  Server_id: 1
End_log_pos: 2134
       Info: COMMIT /* xid=106 */
*************************** 4. row ***************************
   Log_name: mysql-bin.000017
        Pos: 2134
 Event_type: Query
  Server_id: 1
End_log_pos: 2213
       Info: BEGIN
*************************** 5. row ***************************
   Log_name: mysql-bin.000017
        Pos: 2213
 Event_type: Query
  Server_id: 1
End_log_pos: 2310
       Info: use `mydb`; insert into t1 select 9
*************************** 6. row ***************************
   Log_name: mysql-bin.000017
        Pos: 2310
 Event_type: Xid
  Server_id: 1
End_log_pos: 2341
       Info: COMMIT /* xid=107 */
6 rows in set (0.00 sec)

From the above results, we need to skip two transactions (Pos: 1999 insert, Pos: 2103 commit)
Skip operation:

mysql>stop slave;
mysql>SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 2;        Skip a transaction
mysql>start slave;
mysql> show slave statusG
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    3
Current database: mydb

*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 192.168.247.128
                  Master_User: repl
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000017
          Read_Master_Log_Pos: 3613
               Relay_Log_File: DBtest1-relay-bin.000018
                Relay_Log_Pos: 283
        Relay_Master_Log_File: mysql-bin.000017
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB: 
          Replicate_Ignore_DB: 
           Replicate_Do_Table: 
       Replicate_Ignore_Table: 
      Replicate_Wild_Do_Table: 
  Replicate_Wild_Ignore_Table: 
                   Last_Errno: 0
                   Last_Error: 
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 3613
              Relay_Log_Space: 458
              Until_Condition: None
               Until_Log_File: 
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File: 
           Master_SSL_CA_Path: 
              Master_SSL_Cert: 
            Master_SSL_Cipher: 
               Master_SSL_Key: 
        Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error: 
               Last_SQL_Errno: 0
               Last_SQL_Error: 
  Replicate_Ignore_Server_Ids: 
             Master_Server_Id: 1
                  Master_UUID: f0f7faf6-51a8-11e3-9759-000c29eed3ea
             Master_Info_File: /var/lib/mysql/master.info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
           Master_Retry_Count: 86400
                  Master_Bind: 
      Last_IO_Error_Timestamp: 
     Last_SQL_Error_Timestamp: 
               Master_SSL_Crl: 
           Master_SSL_Crlpath: 
           Retrieved_Gtid_Set: 
            Executed_Gtid_Set: 
                Auto_Position: 0
1 row in set (0.01 sec)

The replication status is normal.

В процессе длительной работы с двумя и более MySQL баз данных, между которым происходит репликация, можно столкнуться с массой мелких ошибок, вызванных, например, конфликтами первичных ключей, повреждениями журналов и т.п. Особенно, если репликация настроена, как мастер-мастер, конфликты гарантированы. Естественно, из-за мелких ошибок никто не станет полностью заново синхронизировать две базы данных, а скорее всего, пропустит ошибку через установку SQL_SLAVE_SKIP_COUNTER или slave-skip-errors. Со временем, две БД накопят некий запас неконсистентности, благодаря таким пропущенным конфликтам. Итак, что делать, если нужно восстановить полную консистентность, или в случае, когда ошибка в репликации совсем критичная и не решается вышеописанными способами? Единственный выход — полная синхронизация двух БД «с нуля» и сброс состояния репликации.

Порядок действий таков — на мастере:

mysql-master> STOP SLAVE;
mysql-master> RESET MASTER;
mysql-master> FLUSH TABLES WITH READ LOCK;
mysql-master> SHOW MASTER STATUS;
+------------+----------+--------------------+------------------------+---------------+--------+--------------+---------------+
| File           | Position | Binlog_Do_DB | Binlog_Ignore_DB  |  bin.000002 |     654 |                    | mysql            |
+------------+----------+--------------------+------------------------+---------------+--------+--------------+----------------+

Сохраните вывод последней команды. Первая команда нужна только в случае мастер-мастер репликации. Вторая и третья команды сотрут все журналы мастера, предназначенные для слейвов и переведут все таблицы в режим только чтения, чтобы во время переноса дампа не появилось никаких новых данных.

Далее, не закрывая соединения с мастер базой (т.к. это снимет режим только чтения), делаем дамп всех необходимых данных:

 [user@master ~]$ mysqldump -uroot -p --all-database > ./mysqldump.sql 

Теперь можно снять режим чтения командой

mysql-master> UNLOCK TABLES;

Следующий шаг — скопировать дамп на слейв сервер и выполнить там:

mysql-slave> STOP SLAVE; 

Импортируем загруженный с мастер сервера дамп:

[user@slave1 ~]$ mysql -uroot -p < mysqldump.sql span="">

Далее на слейве удаляем все журналы от мастера и начинаем репликацию с момента, когда на мастере был сделан дамп:

mysql-slave> RESET SLAVE;
mysql-slave> CHANGE MASTER TO MASTER_LOG_FILE = [записанный ранее File], MASTER_LOG_POS =[записанный ранее Position];
mysql-slave> START SLAVE;
mysql-slave> SHOW SLAVE STATUS;

Убеждаемся в том, что параметры Slave_IO_Running и Slave_SQL_Running установлены в Yes. В случае, если у вас мастер-мастер репликация, продолжаем на слейв сервере:

mysql-slave> STOP SLAVE;
mysql-slave> FLUSH TABLES WITH READ LOCK;
mysql-slave> RESET MASTER;
mysql-slave> SHOW MASTER STATUS;+------------+----------+--------------+------------------+
| File       | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------+----------+--------------+------------------+
| bin.000006 |       12 |              | mysql            |
+------------+----------+--------------+------------------+

Снова запоминаем File и Position и на мастер сервере делаем:

mysql-master> CHANGE MASTER TO MASTER_LOG_FILE=[записанный File], MASTER_LOG_POS=[записанный Position];
mysql-master> START SLAVE;
mysql-master> SHOW SLAVE STATUS G;

Убеждаемся в том, что параметры Slave_IO_Running и Slave_SQL_Running установлены в Yes.

На слейве снимаем лок и запускаем репликацию:

mysql-slave> UNLOCK TABLES;
mysql-slave> START SLAVE;

Подробнее о настройке мастер-мастер репликации с нуля можно прочитать

— See more at: http://www.sover.pro/blogs/54-sinhronizaciya-mysql-baz-posle-oshibki-replikacii.html#sthash.uf9cRY0w.dpu

 
Ошибка «Error 1292: Incorrect date / datetime value» при синхронизации
Суть проблемы: чаще всего такая ошибка возникает при попытке синхронизации с таблицей, в которой есть запись со значением ‘0000-00-00’ или ‘0000-00-00 00:00:00’ в полях типа DATE или DATETIME соответственно. В некоторых случаях настройки MySQL позволяют создавать такие записи, но не позволяют редактировать схему таблицы.

Решение: вообще, при синхронизации или экспорте данных MySQL Workbench добавляет специальные запросы, как бы оборачивая основной SQL код:

invalid-dates-solution

Вчитавшись в этот код, начинаешь думать, что программа пытается решить эту проблему самостоятельно. Парадокс в том, что для решения проблемы эти строки нужно удалить:

SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
...
SET SQL_MODE=@OLD_SQL_MODE;

Ошибка «Error 1005: Can’t create table ‘…’ (errno: 150)» при синхронизации
Суть проблемы: обычно эта ошибка касается неправильной настройки внешних ключей (вкладка «Foreign Keys» в настройках таблиц). У меня она возникала в том случае, если я делал ключом поле с меткой NOT NULL, а в поведении внешнего ключа указывал SET NULL — это абсурд, ведь InnoDB не сможет установить значение NULL в поле, где такое значение запрещено.

Решение: внимательно следим за настройкой поведения внешних ключей. Если необходимо поведение SET NULL, у поля-ключа в дочерней таблице не должен стоять флаг NOT NULL.
Ошибка «Field … can not be null» при выгрузке стартовых данных
Суть проблемы: независимо от настроек таблицы, все поля в «Inserts» имеют по умолчанию значение NULL, даже если такое значение не разрешено для данного поля. Соответственно, при выгрузке на сервер может возникнуть ошибка.

Решение: при добавлении стартовых данных следим за тем, чтобы значение NULL оставалось лишь в тех полях, где это разрешено. Если нужно сделать поле пустой строкой, делаем финт ушами: ставим в него курсор, нажимаем пробел, затем стираем его (во всяком случае, я не придумал ничего получше на такой случай :)).
Ошибка Сan’t connect to MySQL server on … (10061) при подключении
Суть проблемы: говорят, что может быть несколько причин. Я встечал такую ошибку в случае, если в файле my.cnf была установлена настройка «skip-networking» — по сути она не даёт MySQL работать с сетью.

Решение: закомментировать данную опцию:

 


February 13, 2008




2-minute read

Normally MySQL replication will stop whenever there is an error running a query on the slave. This happens in order for us to be able to identify the problem and fix it, and keep the data consistent with the mater that has sent the query. You can skip such errors, even if this is not recommended, as long as you know really well what are those queries and why they are failing, etc.

For example you can skip just one query that is hanging the slave using:

mysql>SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; START SLAVE;

There might be cases where you will want to skip more queries. For example you might want to skip all duplicate errors you might be getting (output from show slave status;):

"1062 | Error 'Duplicate entry 'xyz' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO ..."

If you are sure that skipping those errors will not bring your slave inconsistent and you want to skip them ALL, you would add to your my.cnf:

As shown above in my example 1062 is the error you would want to skip, and from here we have:
Error: 1062 SQLSTATE: 23000 (ER_DUP_ENTRY)
Message: Duplicate entry ‘%s’ for key %d

You can skip also other type of errors, but again don’t do this unless you understand very well what those queries are and what impact they have on your data:

slave-skip-errors=[err_code1,err_code2,...|all]

and for the error codes you can see them all here … (you will see them in your show slave status; also).

  • Myphoneexplorer ошибка получения ip адреса телефона
  • Myphoneexplorer ошибка obex errorcode c1 unauthorized
  • Myhomelib код ошибки 11001
  • Myhomelib архив не найден ошибка
  • Myfitnesspal ошибка при регистрации