55.3. Как устанавливаются соединения #
Postgres Pro Shardman реализует простую клиент-серверную модель по схеме «процесс для пользователя». В такой схеме один клиентский процесс подключается к одному отдельному серверному процессу. Так как мы не знаем заранее, сколько подключений будет, нам нужен «главный процесс», который будет запускать новый процесс при каждом запросе подключения. Главный процесс называется postmaster и принимает входящие подключения в заданном порту TCP/IP. Получив запрос на подключение, процесс postgres порождает новый серверный процесс. Серверные задачи взаимодействуют между собой и другими процессами экземпляра СУБД через семафоры и разделяемую память, чтобы обеспечить целостность данных при одновременном обращении к ним.
В отличие от монолитных систем, в распределённом кластере требуется единообразие и видимость во всех экземплярах СУБД, у каждого из которых свои сеансы и подключения. Основная задача при таком сценарии — это обеспечить работу распределённых транзакций от лица разных пользователей (единая точка подключения для клиентских соединений). Postgres Pro Shardman позволяет производить авторизацию на сторонних серверах от лица операционного пользователя, для которого на всех узлах кластера настроен SSL-сертификат. В момент прохождения SQL-запроса от лица конкретного пользователя соединение устанавливается от лица такого операционного пользователя. Однако как только сеанс начинается, ИД пользователя меняется на ИД того пользователя, который инициировал запрос на координаторе, с сохранением всех прав.
В то же время доверенные пользователи могут авторизоваться по SSL-сертификату (через авторизацию libpq), который генерируются для каждого сервера или кластера.
За подробной информацией обратитесь к схеме:
Рисунок 55.5. Схема подключения
В Postgres Pro Shardman также есть альтернативное приложение для транспорта – Silk.
Обратите внимание, что клиентским процессом может быть любая программа, которая понимает протокол Postgres Pro Shardman, описанный в Главе 58. Многие клиенты базируются на библиотеке libpq для языка C, но есть и другие независимые реализации этого протокола, например, драйвер JDBC для Java.
Установив подключение, клиентский процесс может передать запрос серверу. Запрос передаётся в обычном текстовом виде, клиент не занимается его анализом. Сервер разбирает запрос, строит план выполнения, выполняет его и возвращает полученные строки клиенту, передавая их через установленное подключение.
55.3. How Connections Are Established #
Postgres Pro Shardman implements a “process per user” client/server model. In this model, every client process connects to exactly one backend process. As we do not know ahead of time how many connections will be made, we have to use a “supervisor process” that spawns a new backend process every time a connection is requested. This supervisor process is called postmaster and listens at a specified TCP/IP port for incoming connections. Whenever it detects a request for a connection, it spawns a new backend process. Those backend processes communicate with each other and with other processes of the instance using semaphores and shared memory to ensure data integrity throughout concurrent data access.
Unlike single-instance systems, the distributed clusters require consistency and visibility across DBMS instances, with each of them working with its own sessions and connections. The key task here is to guarantee the distributed transactions on behalf of different users (single connection point for client connections). Postgres Pro Shardman allows authorization on foreign servers to be handled by a single service user that has SSL certificate configured for on all node clusters. At the moment of an SQL query on behalf of the specific user, a connection is established under the service user profile. Once the session is going, the user ID is changed to the ID of the user that initiated the query on the coordinator, all privileges applied.
At the same time, trusted users can authorize with the SSL certificate (based on libpq) that is generated per server or cluster.
See the following chart for details:
Figure 55.5. Connection Flow Chart
Postgres Pro Shardman also has an alternative transport feature, Silk.
Note that the client process can be any program that understands the Postgres Pro Shardman protocol described in Chapter 58. Many clients are based on the C-language library libpq, but several independent implementations of the protocol exist, such as the Java JDBC driver.
Once a connection is established, the client process can send a query to the backend process it's connected to. The query is transmitted using plain text, i.e., there is no parsing done in the client. The backend process parses the query, creates an execution plan, executes the plan, and returns the retrieved rows to the client by transmitting them over the established connection.