Статьи

Высокая доступность с MySQL Fabric: Часть I

Этот пост был изначально написан Мартином Арриета

В нашем предыдущем посте мы представили утилиту MySQL Fabric и сказали, что углубимся в нее. Этот пост является первой частью нашего теста функциональности высокой доступности (HA) MySQL Fabric.

Сегодня мы рассмотрим концепции высокой доступности MySQL Fabric, а затем проведем вас через настройку 3-узлового кластера с одним основным и двумя дополнительными компьютерами, выполнив несколько базовых тестов с ним. Во втором посте мы уделим больше времени созданию сценариев сбоев и документированию того, как их обрабатывает Fabric. (MySQL Fabric — это расширяемая инфраструктура для управления большими фермами серверов MySQL с поддержкой высокой доступности и шардинга.)

Прежде чем мы начнем, мы рекомендуем вам прочитать  эту статью Матса Киндала из Oracle, в которой, среди прочего, рассматриваются вопросы, которые мы затронули в нашей первой публикации. Матс возглавляет команду MySQL Fabric.

Наша лаборатория

Все наши тесты будут использовать нашу тестовую среду с Vagrant ( https://github.com/martinarrieta/vagrant-fabric )

Если вы хотите поиграть с MySQL Fabric, эти виртуальные машины могут быть запущены на вашем рабочем столе, следуя инструкциям в файле README. Если вам не нужны полноценные виртуальные машины, наш коллега Джервин Реал создал набор сценариев- оболочек, которые позволяют вам тестировать MySQL Fabric с помощью песочниц.

Вот основное представление о нашей среде.

Ткань Лаборатория

Настроить

Чтобы настроить MyQSL ткань без использования нашей окружающей среды Vagrant, вы можете следовать официальной документации , или проверить анзибль playbooks в нашей лаборатории репо. Если вы следуете руководству, единственное предостережение заключается в том, что при создании пользователя вы должны либо отключить бинарное ведение журнала для своего сеанса, либо использовать инструкцию GRANT вместо CREATE USER. Вы можете прочитать здесь  для получения дополнительной информации о том, почему это так.

Описание всех параметров в файле конфигурации можно найти здесь . Что касается тестов HA, то стоит упомянуть, что по нашему опыту детектор сбоев будет запускать автоматический переход на другой ресурс только в том случае, если значение для failover_interval в разделе [fail_tracking] больше 0. В противном случае сбои будут обнаружены и записаны в журнал, но никаких действий предприниматься не будет.

Конфигурация MySQL

Чтобы управлять экземпляром mysqld с MySQL Fabric, в разделе [mysqld] его файла my.cnf необходимо установить следующие параметры:

log_bin
gtid-mode=ON
enforce-gtid-consistency
log_slave_updates

Кроме того, как и при любой настройке репликации, вы должны убедиться, что все серверы имеют разные идентификаторы server_id .

Когда все будет готово, вы можете настроить и запустить MySQL Fabric с помощью следующих команд:

[vagrant@store ~]$ mysqlfabric manage setup
[vagrant@store ~]$ mysqlfabric manage start --daemon

Команда setup создает схему базы данных, используемую MySQL Fabric для хранения информации об управляемых серверах, а стартовая , ну, в общем, запускает демон. Опция –daemon запускает Fabric как демон, регистрируя файл вместо стандартного вывода. В зависимости от порта и имени файла, которые вы настроили в fabric.cfg, это может потребоваться для запуска от имени пользователя root.

Во время тестирования вы можете заставить MySQL Fabric сбросить свое состояние в любое время (хотя это не изменит существующие конфигурации узлов, такие как репликация), выполнив:

[vagrant@store ~]$ mysqlfabric manage teardown
[vagrant@store ~]$ mysqlfabric manage setup

Если вы используете нашу среду Vagrant, вы можете запустить сценарий reinit_cluster.sh из своей операционной системы (из корня репозитория vagrant -fabric), чтобы сделать это для вас, а также инициализировать datadir трех экземпляров.

Создание кластера высокой доступности:

Кластер высокой доступности — это набор серверов, использующих стандартную асинхронную репликацию MySQL с GTID.

Создание группы

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

$ mysqlfabric group create <group_name>

В нашем примере для создания кластера «mycluster» вы можете запустить:

[vagrant@store ~]$ mysqlfabric group create mycluster
Procedure :
{ uuid        = 605b02fb-a6a1-4a00-8e24-619cad8ec4c7,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}

Добавьте серверы в группу

Второй шаг — добавить серверы в группу. Синтаксис для добавления сервера в группу:

$ mysqlfabric group add <group_name> <host_name or IP>[:port]

Номер порта является необязательным и требуется только если он отличается от 3306. Важно отметить, что клиенты, которые будут использовать этот кластер, должны иметь возможность разрешать этот хост или IP. Это связано с тем, что клиенты будут напрямую подключаться как к серверу XML-PRC MySQL Fabric, так и к управляемым серверам mysqld. Давайте добавим узлы в нашу группу.

[vagrant@store ~]$ for i in 1 2 3; do mysqlfabric group add mycluster node$i; done
Procedure :
{ uuid        = 9d65c81c-e28a-437f-b5de-1d47e746a318,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}
Procedure :
{ uuid        = 235a7c34-52a6-40ad-8e30-418dcee28f1e,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}
Procedure :
{ uuid        = 4da3b1c3-87cc-461f-9705-28a59a2a4f67,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}

Promote a node as a master

Now that we have all our nodes in the group, we have to promote one of them. You can promote one specific node or you can let MySQL Fabric to choose one for you.

The syntax to promote a specific node is:

$ mysqlfabric group promote <group_name> --slave_uuid='<node_uuid>'

or to let MySQL Fabric pick one:

$ mysqlfabric group promote <group_name>

Let’s do that:

[vagrant@store ~]$ mysqlfabric group promote mycluster
Procedure :
{ uuid        = c4afd2e7-3864-4b53-84e9-04a40f403ba9,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}

You can then check the health of the group like this:

[vagrant@store ~]$ mysqlfabric group health mycluster
Command :
{ success     = True
  return      = {'e245ec83-d889-11e3-86df-0800274fb806': {'status': 'SECONDARY', 'is_alive': True, 'threads': {}}, 'e826d4ab-d889-11e3-86df-0800274fb806': {'status': 'SECONDARY', 'is_alive': True, 'threads': {}}, 'edf2c45b-d889-11e3-86df-0800274fb806': {'status': 'PRIMARY', 'is_alive': True, 'threads': {}}}
  activities  =
}

One current limitation of the ‘health’ command is that it only identifies servers by their uuid. To get a list of the servers in a group, along with quick status summary, and their host names, use lookup_servers instead:

[vagrant@store ~]$ mysqlfabric group lookup_servers mycluster
Command :
{ success     = True
  return      = [{'status': 'SECONDARY', 'server_uuid': 'e245ec83-d889-11e3-86df-0800274fb806', 'mode': 'READ_ONLY', 'weight': 1.0, 'address': 'node1'}, {'status': 'SECONDARY', 'server_uuid': 'e826d4ab-d889-11e3-86df-0800274fb806', 'mode': 'READ_ONLY', 'weight': 1.0, 'address': 'node2'}, {'status': 'PRIMARY', 'server_uuid': 'edf2c45b-d889-11e3-86df-0800274fb806', 'mode': 'READ_WRITE', 'weight': 1.0, 'address': 'node3'}]
  activities  =
}

We sent a merge request to use a Json string instead of the “print” of the object in the “return” field from the XML-RPC in order to be able to use that information to display the results in a friendly way. In the same merge, we have added the address of the servers in the health command too.

Failure detection

Now we have the three lab machines set up in a replication topology of one master (the PRIMARY server) and two slaves (the SECONDARY ones). To make MySQL Fabric start monitoring the group for problems, you need to activate it:

[vagrant@store ~]$ mysqlfabric group activate mycluster
Procedure :
{ uuid        = 230835fc-6ec4-4b35-b0a9-97944c18e21f,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}

Now MySQL Fabric will monitor the group’s servers, and depending on the configuration (remember the failover_interval we mentioned before) it may trigger an automatic failover. But let’s start testing a simpler case, by stopping mysql on one of the secondary nodes:

[vagrant@node2 ~]$ sudo service mysqld stop
Stopping mysqld:                                           [  OK  ]

And checking how MySQL Fabric report’s the group’s health after this:

[vagrant@store ~]$ mysqlfabric group health mycluster
Command :
{ success     = True
  return      = {'e245ec83-d889-11e3-86df-0800274fb806': {'status': 'SECONDARY', 'is_alive': True, 'threads': {}}, 'e826d4ab-d889-11e3-86df-0800274fb806': {'status': 'FAULTY', 'is_alive': False, 'threads': {}}, 'edf2c45b-d889-11e3-86df-0800274fb806': {'status': 'PRIMARY', 'is_alive': True, 'threads': {}}}
  activities  =
}

We can see that MySQL Fabric successfully marks the server as faulty. In our next post we’ll show an example of this by using one of the supported connectors to handle failures in a group, but for now, let’s keep on the DBA/sysadmin side of things, and try to bring the server back online:

[vagrant@node2 ~]$ sudo service mysqld start
Starting mysqld:                                           [  OK  ]
[vagrant@store ~]$ mysqlfabric group health mycluster
Command :
{ success     = True
  return      = {'e245ec83-d889-11e3-86df-0800274fb806': {'status': 'SECONDARY', 'is_alive': True, 'threads': {}}, 'e826d4ab-d889-11e3-86df-0800274fb806': {'status': 'FAULTY', 'is_alive': True, 'threads': {}}, 'edf2c45b-d889-11e3-86df-0800274fb806': {'status': 'PRIMARY', 'is_alive': True, 'threads': {}}}
  activities  =
}

So the server is back online, but Fabric still considers it faulty. To add the server back into rotation, we need to look at the server commands:

[vagrant@store ~]$ mysqlfabric help server
Commands available in group 'server' are:
    server set_weight uuid weight  [--synchronous]
    server lookup_uuid address
    server set_mode uuid mode  [--synchronous]
    server set_status uuid status  [--update_only] [--synchronous] 

The specific command we need is set_status, and in order to add the server back to the group, we need to change it’s status twice: first to SPARE and then back to SECONDARY. You can see what happens if we try to set it to SECONDARY directly:

[vagrant@store ~]$ mysqlfabric server set_status e826d4ab-d889-11e3-86df-0800274fb806 SECONDARY
Procedure :
{ uuid        = 9a6f2273-d206-4fa8-80fb-6bce1e5262c8,
  finished    = True,
  success     = False,
  return      = ServerError: Cannot change server's (e826d4ab-d889-11e3-86df-0800274fb806) status from (FAULTY) to (SECONDARY).,
  activities  =
}

So let’s try it the right way:

[vagrant@store ~]$ mysqlfabric server set_status e826d4ab-d889-11e3-86df-0800274fb806 SPARE
Procedure :
{ uuid        = c3a1c244-ea8f-4270-93ed-3f9dfbe879ea,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}
[vagrant@store ~]$ mysqlfabric server set_status e826d4ab-d889-11e3-86df-0800274fb806 SECONDARY
Procedure :
{ uuid        = 556f59ec-5556-4225-93c9-b9b29b577061,
  finished    = True,
  success     = True,
  return      = True,
  activities  =
}

And check the group’s health again:

[vagrant@store ~]$ mysqlfabric group health mycluster
Command :
{ success     = True
  return      = {'e245ec83-d889-11e3-86df-0800274fb806': {'status': 'SECONDARY', 'is_alive': True, 'threads': {}}, 'e826d4ab-d889-11e3-86df-0800274fb806': {'status': 'SECONDARY', 'is_alive': True, 'threads': {}}, 'edf2c45b-d889-11e3-86df-0800274fb806': {'status': 'PRIMARY', 'is_alive': True, 'threads': {}}}
  activities  =
}

In our next post, when we discuss how to use the Fabric aware connectors, we’ll also test other failure scenarios like hard VM shutdown and network errors, but for now, let’s try the same thing but on the PRIMARY node instead:

[vagrant@node3 ~]$ sudo service mysqld stop
Stopping mysqld:                                           [  OK  ]

And let’s check the servers again:

[vagrant@store ~]$ mysqlfabric group lookup_servers mycluster
Command :
{ success     = True
  return      = [{'status': 'SECONDARY', 'server_uuid': 'e245ec83-d889-11e3-86df-0800274fb806', 'mode': 'READ_ONLY', 'weight': 1.0, 'address': 'node1'}, {'status': 'PRIMARY', 'server_uuid': 'e826d4ab-d889-11e3-86df-0800274fb806', 'mode': 'READ_WRITE', 'weight': 1.0, 'address': 'node2'}, {'status': 'FAULTY', 'server_uuid': 'edf2c45b-d889-11e3-86df-0800274fb806', 'mode': 'READ_WRITE', 'weight': 1.0, 'address': 'node3'}]
  activities  =
}

We can see that MySQL Fabric successfully marked node3 as FAULTY, and promoted node2 to PRIMARY to resolve this. Once we start mysqld again on node3, we can add it back as SECONDARY using the same process of setting it’s status to SPARE first, as we did for node2 above.

Remember that unless failover_interval is greater than 0, MySQL Fabric will detect problems in an active group, but it won’t take any automatic action. We think it’s a good thing that the value for this variable in the documentation is 0, so that automatic failover is not enabled by default (if people follow the manual, of course), as even in mature HA solutions like Pacemaker, automatic failover is something that’s tricky to get right. But even without this, we believe the main benefit of using MySQL Fabric for promotion is that it takes care of reconfiguring replication for you, which should reduce the risk for error in this process, specially once the project becomes GA.

What’s next

In this post we’ve presented a basic replication setup managed by MySQL Fabric and reviewed a couple of failure scenarios, but many questions are left unanswered, among them:

  • What happens to clients connected with a Fabric aware driver when there is a status change in the cluster?
  • What happens when the XML-RPC server goes down?
  • How can we improve its availability?

We’ll try to answer these and other questions in our next post. If you have some questions of your own, please leave them in the comments section and we’ll address them in the next or other posts, depending on the topic.