# Главная
# О библиотеке

# Выбор дистрибутива
преимущества Linux/UNIX | основные дистрибутивы | серверный Linux | BSD | LiveCDs | прочее

# Установка и удаление программ
общие вопросы | каталоги софта | специальные случаи

# Настройка и работа
установка, загрузчики | настройка Linux | консоль | файловые системы | процессы | шеллы, русификация, коммандеры | виртуальные машины, эмуляторы

# X Window и оконные менеджеры
настройка X Window | GNOME | KDE | IceWM и др.

# Работа с текстами
редакторы | офис | шрифты, кодировки и русификация | преобразования текстовых файлов | LaTeX, SGML и др. | словари

# Графика
GIMP | фото | обработка изображений | форматы графических файлов

# Сети, администрирование
общие вопросы | Dialup & PPP | брандмауэры | маршрутизация | работа в Windows-сетях | веб-серверы | Apache | прокси-серверы | сетевая печать | прочее

# Программирование
GCC & GNU make | программирование в UNIX | графические библиотеки | Tcl | Perl | PHP | Java & C# | СУБД | CVS | прочее

# Ядро
# Мультимедиа
# Интернет
# Почта
# Безопасность
# Железо
# Разное

# Linux HowTo (как сделать)
# Книги и руководства
# Материалы на английском языке


MySQL The World's Most Popular Open Source Database # Online shop | Site map |  
CompanyProductsSupport & ConsultingTraining & CertificationDownloadsDocumentation
  BooksArticlesMailing ListsPresentationsOther Sites  
Search the MySQL manual:
MySQL Manual
  • 4 Администрирование баз данных
    • 4.10 Репликация в MySQL
      • 4.10.1 Введение
      • 4.10.2 Как реализована репликация: обзор
      • 4.10.3 Как настроить репликацию
      • 4.10.4 Возможности репликации и известные проблемы
      • 4.10.5 Опции репликации в файле `my.cnf'
      • 4.10.6 SQL-команды, относящиеся к репликации
      • 4.10.7 Часто задаваемые вопросы по репликации
      • 4.10.8 Поиск неисправностей репликации

Buy this Reference Manual in softcover from Barnes & Noble!

MySQL Reference Manual
Previous / Next / Up / Table of Contents

4.10.8 Поиск неисправностей репликации

Если вы следовали инструкциям, но установленный механизм репликации не работает, прежде всего следует искать пользовательские ошибки. Выполните следующие проверки:

  • Производит ли головной сервер записи в двоичный журнал? Проверьте это при помощи команды SHOW MASTER STATUS. Если да, значение Position будет отличным от нуля. Если нет, проверьте, запущен ли головной сервер с опцией log-bin и установлен ли server-id.
  • Запущен ли подчиненный сервер? Проверьте это при помощи команды SHOW SLAVE STATUS. Ответ находится в столбце Slave_running. Если нет, проверьте опции подчиненного сервера и просмотрите сообщения в журнале ошибок.
  • Если подчиненный сервер запущен, установил ли он соединение с головным сервером? Выполните команду SHOW PROCESSLIST, найдите поток, которому соответствует значение system user в столбце User и none в столбце Host, и проверьте столбец State. Если в нем находится значение connecting to master, проверьте привилегии для пользователя репликации на головном сервере, имя хоста головного сервера, установку DNS, посмотрите, запущен ли головной сервер в текущее время, доступен ли он для подчиненного сервера. После этого, если все окажется в порядке, просмотрите журналы ошибок.
  • Если подчиненный сервер был запущен, но затем остановился, посмотрите на вывод команды SHOW SLAVE STATUS и проверьте журналы ошибок. Такое обычно случается, когда некоторый запрос, успешно выполняющийся на головном сервере, не выполняется на подчиненном. Если создан корректный образ головного сервера и данные на подчиненном сервере обновлялись только через поток подчиненного сервера, этого происходить не должно. Но если все же такое случилось - значит, имеет место ошибка; как сообщить о ней, читайте ниже.
  • Если запрос, успешно выполняемый на головном сервере, не выполняется на подчиненном, и нельзя выполнить полную ресинхронизацию базы данных (ее стоит выполнить), попробуйте сделать следующее:
    • Сначала проверьте: возможно где-либо случайно оказалась ненужная запись. Разберитесь, как она оказалась там, затем удалите ее, и выполните команду SLAVE START.
    • Если вы проделали все, о чем написано выше, и ничего не помогло или этого сделать нельзя, попытайтесь понять, будет ли безопасно выполнить обновления вручную (если необходимо) и после этого игнорировать следующий запрос от головного сервера.
    • Если вы решили пропустить следующий запрос, выполните команды SET SQL_SLAVE_SKIP_COUNTER=1; SLAVE START; чтобы пропустить запрос, не использующий функции AUTO_INCREMENT или LAST_INSERT_ID(). В противном случае выполните команды SET SQL_SLAVE_SKIP_COUNTER=2; SLAVE START. Причина того, что запросы, использующие функции AUTO_INCREMENT или LAST_INSERT_ID(), обрабатываются по-другому, заключается в том, что они создают два события в двоичном журнале головного сервера.
    • Если вы уверены, что подчиненный сервер был успешно запущен и синхронизирован с головным сервером, а также что обновления таблиц не производились вне потока подчиненного сервера, пришлите нам отчет об ошибке, и вам не потребуется опять повторять описанные выше уловки.
  • Удостоверьтесь, что вы не внесли старой ошибки при апгрейде MySQL до более новой версии.
  • Если ничего не помогает, просмотрите журналы ошибок. Если журналы большие, выполните команду grep -i slave /path/to/your-log.err на подчиненном сервере. Искать ошибку на головном сервере - не лучшая идея, поскольку в его журналах находятся лишь системные ошибки общего характера; если это возможно, он посылает ошибку на подчиненный сервер, когда что-либо происходит не так, как надо.

Если вы убедились, что пользовательская ошибка здесь ни при чем, однако механизм репликации по-прежнему не работает или работает нестабильно, пришло время начать работу над отчетом об ошибке. Вы должны предоставить нам столько информации, сколько нужно, чтобы отследить ошибку. Пожалуйста, уделите отчету об ошибке нужное количество времени и усилий, чтобы сделать его хорошо. В идеале мы хотели бы иметь контрольный пример в формате, который находится в каталоге `mysql-test/t/rpl*' исходного дерева. Отослав такой контрольный пример, в большинстве случаев можно рассчитывать на получение патча в течение одного-двух дней, хотя, конечно, это время может варьироваться в зависимости от множества факторов.

Еще один хороший способ проинформировать нас об ошибке - написать простую программу с легко конфигурируемыми параметрами соединения для головного и подчиненного серверов, в которой будет продемонстрирована проблема наших систем. Программа может быть написана на Perl или на C, в зависимости от того, какой язык вы знаете лучше.

Подготовив информацию об ошибке одним из двух способов, используйте утилиту mysqlbug, чтобы создать отчет об ошибке, и пошлите его по адресу [email protected]. Если же вы имеете дело с фантомом - проблемой, которая имеет место, но вы по какой-либо причине не можете ее воспроизвести по желанию:

  • Убедитесь, что эта проблема не вызвана пользовательской ошибкой. Например, при обновлении подчиненного сервера вне потока подчиненного сервера данные будут не синхронизированы, и могут быть нарушения уникальных ключей при обновлениях. В этом случае поток подчиненного сервера остановится и будет ждать, пока таблицы не будут очищены вручную, для приведения их в синхронизированный режим.
  • Запустите подчиненный сервер с опциями log-slave-updates и log-bin - при этом в журнал будет заноситься информация обо всех обновлениях, происходящих на подчиненном сервере.
  • Сохраните все доказательства наличия ошибки перед сбросом репликации. Если у нас нет информации о проблеме, или имеется только отрывочная информация, потребуется время, чтобы найти источник проблемы. Вы должны собрать следующие "свидетельства":
    • Все двоичные журналы головного сервера
    • Весь двоичный журнал подчиненного сервера
    • Вывод команды SHOW MASTER STATUS на головном сервере во время обнаружения проблемы
    • Вывод команды SHOW SLAVE STATUS на головном сервере во время обнаружения проблемы
    • Журналы ошибок головного сервера и подчиненного сервера
  • Для изучения двоичных журналов используйте утилиту mysqlbinlog. Таким образом можно находить проблемные запросы, например:
    mysqlbinlog -j pos_from_slave_status /path/to/log_from_slave_status | head
    

Собрав "свидетельства" о проблеме-фантоме, попробуйте сначала организовать их в отдельный контрольный пример. После этого сообщите о проблеме по адресу [email protected], описав эту проблему во всех подробностях.

User Comments

Posted by Matt Warnock on Friday May 17 2002, @6:24am[Delete] [Edit]

Note that the default MySQL port is 3306 and that
this is the number that should normally be
specified in my.cnf on the slaves.

This info is given in the replication config file
page, but should be listed here too. You won't
find it under "ports" or "connections" in the
subject index.

Also, is this statement optional if the slaves
connect at the same port that they listen on?

Posted by [name withheld] on Friday May 17 2002, @6:24am[Delete] [Edit]

Note that if you client does not do a "USE
dbname", binlog-do-db=dbname will not binlog a
query like: "update in dbname.foobar set foo=1"

You explicitly have to do a USE before a query in
order to have your query binlogged, it looks
like. Replication on the slave side can do
wildcard matches .. but the master cannot (a la
binlog-wild-do-table=dbname.%). So make sure your
clients do a use, if you plan to replicate those
tables it updates.

Posted by [name withheld] on Friday May 17 2002, @6:24am[Delete] [Edit]

for MySQL v3.23.28:
When you attempt to use a certain master-
user/master-password combo to connect to the
mysql master, and you later change my.cnf to
attempt to connect with a new user, you must
update master.info to reflect the changes.

Since my master.info file only had one entry in
it (the slave only has one master), I simply
deleted the file. Upon restarting the slave
daemon, a new master.info was automatically
written.

--Curby

Posted by Ed McGuigan on Friday May 17 2002, @6:24am[Delete] [Edit]

If you need to roll your own log file rotation
script as I did, and you are familiar with Perl,
look at the Log::Rotate module on CPAN rather
than reinventing the wheel.

Posted by Brian Duggan on Friday May 17 2002, @6:24am[Delete] [Edit]

Using release 3.23.42-1, the grant file command
didn't work for me when specifying a specific
database, and I found it necessary to modify the
File_priv column in the user table directly.

Posted by Renato Golin on Friday May 17 2002, @6:24am[Delete] [Edit]

If you intend to use "load table from master" you need to have access to that table to "rep" user, unlike this sections says of only having to set "File_priv" to "rep" user for all bases.

Posted by Jesse Thompson on Friday May 17 2002, @6:24am[Delete] [Edit]

Above on this page where it talks about "properly
modularized and abstracted code" and refers to
safe_reader_query() and safe_writer_query(), I'd
like to put forth the proposition that different
abstracted functions for reading and writing need
not be nessessary for compliance with replication.

We currently have all of our queries running
through One safe-sql envelope, and we intend to
keep this architecture as we move to replication
by telling our envelope to send any queries that
begin with /\s+select/i to the slave, and
anything else to the master. We are running under
the assumption that all "read queries" are
selects. I can't think of any that aren't. If
there were they would probably be nominal in
performace draw (we use many complex select
statements :) and wouldn't do any harm being
handled by the master anyway.

So far as multi-statement queries, are code
doesn't, and won't, mix selects in the same query
with non-selects, or probably even use more than
one select per query, since we're not certain
what results could be returned in such a
circumstance. Thus reading and writing should
never get mixed up in the same query, and all
reads should start with the word "Select".

If you feel that my theory holds water then give
it a go, if you see a flaw in my logic before I
do mail me and lemme know, eh? 10x :)

- - Jess

Posted by Jeff Allen on Friday May 17 2002, @6:24am[Delete] [Edit]

When I started up my slave the first time, I had
been using binary logging for some time on the
master. I had already removed $hostname-bin.001
long ago. The slave complained about not being
able to find the first log and would not start
replaying transactions. To fix this, I stopped
the master, made a new snapshot, moved "*-bin.*"
to another directory, and started the master
again. Then when I put the snapshot on the slave
and started it, everything worked correctly.

Posted by Jesse Thompson on Friday May 17 2002, @6:24am[Delete] [Edit]

Above where it says to add options to the slave
machine's /etc/my.cnf, it's not explicit but you
DO need to add them to the [mysqld] section. If
you add them to some other section by mistake
mysql will behave as though it doesn't know you
want it to slave. It will tell you you haven't
configured it to slave, and no errors will occur
in the log.

Good luck with all of your replicating needs :)

- - Jess

Posted by Jonathon Padfield on Friday May 17 2002, @6:24am[Delete] [Edit]


If you want your slaves to connect to the
replication server with a unique username &
password and minimal privileges, you need to grant
just the FILE privilege to your replication user.

Similarly, if your slaves have no local updates
made on them, just lots of selects, its a very
good idea to connect with a user that cannot
update the data. This stops dead any chance of
mistakenly connecting to the wrong DB and losing
updates.

Posted by joshua paul on Friday May 17 2002, @6:24am[Delete] [Edit]

With verion 3.23.41 - I couldn't get replication
to work following the instructions about.
Specifically I got errors when I created
the "repl" user before copying data to the slave.
I could only get replication to work if I created
the "repl" user after copying data to the slave -
and obviously starting both servers...

Posted by Jason de Cordoba on Friday May 17 2002, @6:24am[Delete] [Edit]

Using Mysql 3.23.46 We tried to use the
mysqld option --bind-address=xxx.xxx.xxx.xxx to
bind the slave to a piticular IP address, one
that is directed away from visitor traffic on a
seperate ethernet device. We found in fact
mysqld was only available via the specified ip
but the slave host did not have the same
behavior. Since the slave is running under
mysqld why does --bind-address have no
effect?

Posted by [name withheld] on Friday May 17 2002, @6:24am[Delete] [Edit]

Note: If you are running WinMySQLAdmin, you will
have to make the changes in the my.ini file as
well. It took me a while to realize this.

Posted by Chad Kouse on Friday May 17 2002, @6:24am[Delete] [Edit]

incredibly helpful page. I do have one issue to
raise - I have two servers doing 2-way
replication. One is on Linux, and one is on
Windows. There is an issue of case-sensitivity
in that if case is not taken into consideration
on the windows machine, the slave on the linux
machine stops. I'd love to hear any fixes to
this: [email protected]

Posted by [name withheld] on Friday May 17 2002, @6:24am[Delete] [Edit]

I also had the problem Allen pointed out above,
in my case I had not actually deleted any of the
binary log files which the slave still required
to update from (I knew this courtesy of "show
slave status" command). But I had deleted several
log files it had finished with. I was able to fix
this without making a brand new snapshot (which
in my case took a larger outage that I would
like) What I did was edit the file (in the
Masters logs directory) $hostname-bin.index and
edited entries to show exact filenames of my
remaining binary log files.(ie: removing the
entries matching ones I had deleted manually from
the file system) I quickly did a mysql stop and
mysql start after that and I performed the
command "slave stop; slave start;" on the slave
and it started replicating again. I am running
version 3.23.41

Posted by David Dombek on Thursday January 30 2003, @9:17am[Delete] [Edit]

Mysql 3.23.49
When a slave is running you have a master.info file. If you change the slave to become the master you must delete the master.info file or you may get errors such as this:

030130 10:57:03 Slave thread: error connecting to master: Unknown MySQL Server Host '' (4) (107), retry in 60 sec

It will keep retrying every 60 sec. Just deleting the master.info file worked for me.

Posted by [email protected] on Thursday February 6 2003, @1:59am[Delete] [Edit]

I wouldn't suggest running replication on machines with different os. I had win2000 running MySQL server as well a RedHat Linux 7.3 with MySQL server as well. When the client code on Linux tried to connect to win2000 MySQL server, the server died, with win2000 reporting it has terminated.
Still haven't figure out what happened

Posted by Alban Hasa on Sunday March 9 2003, @10:42am[Delete] [Edit]

If the slave doesn't find the master host, it stays in thread "connectin to master" and at 90% my MySQL Server version 3.23.54 dies.

I made an error during replication setup, I wrote the wrong IP address for the master. But this is a great problem when the master server goes down. Can anyone have a solution for this? Please Help

Add your own comment.

Top / Previous / Next / Up / Table of Contents
# MySQL.com home | Site map | Contact us | Press | Jobs | Privacy policy | Trademark info | © 1995-2003 MySQL AB. All rights reserved.