Compare commits

...
19 Commits
Author SHA1 Message Date
Alexander Kukushkin 4d9720a78d Use pg10 as base image and python3 instead of 2 2018-09-12 16:57:22 +02:00
Alexander Kukushkin 1f205f8191 Merge branch 'master' of github.com:zalando/patroni into feature/demo 2018-09-12 16:44:02 +02:00
Pavel KirillovandAlexander Kukushkin 2e9cb412e4 Register service in consul (#802)
Кegister service 'scope_name' with tag 'master' or 'replica'

example with scope 'pgsql-pgpi'
```[root@pgpi1 ~]# host -t SRV pgsql-pgpi.service.consul. 127.0.0.1
Using domain server:
Name: 127.0.0.1
Address: 127.0.0.1#53
Aliases:

pgsql-pgpi.service.consul has SRV record 1 1 5432 pgpi1.node.dc.consul.
pgsql-pgpi.service.consul has SRV record 1 1 5432 pgpi2.node.dc.consul.
[root@pgpi1 ~]# host -t SRV master.pgsql-pgpi.service.consul. 127.0.0.1
Using domain server:
Name: 127.0.0.1
Address: 127.0.0.1#53
Aliases:

master.pgsql-pgpi.service.consul has SRV record 1 1 5432 pgpi2.node.dc.consul.
[root@pgpi1 ~]# host -t SRV replica.pgsql-pgpi.service.consul. 127.0.0.1
Using domain server:
Name: 127.0.0.1
Address: 127.0.0.1#53
Aliases:

replica.pgsql-pgpi.service.consul has SRV record 1 1 5432 pgpi1.node.dc.consul.```

Fixes: https://github.com/zalando/patroni/issues/771
2018-09-07 15:17:56 +02:00
Dmitry DolgovandGitHub dd7c3c349f [WIP] Standby cluster implementation (#679)
Implementation of "standby cluster" described in #657. Standby cluster consists
of a "standby leader", that replicates from a "remote master" (which is not a
part of current patroni cluster and can be anywhere), and cascade replicas,
that replicate from the corresponding standby leader. "Standby leader" behaves
pretty much like a regular leader, which means that it holds a leader lock in
DSC, in case if disappears there will be an election of a new "standby
leader".
One can define such a cluster using the section "standby_cluster" in patroni
config file. This section provides parameters for standby cluster, that will be
applied only once during bootstrap and can be changed only through DSC.
2018-09-07 10:10:56 +02:00
Alexander KukushkinandGitHub 4ca8a6e506 Make retries of calls to DCS consistent across implementations (#805)
in addition to that do a small refactoring of zookeeper and consul and try to improve the stability of AT
2018-09-06 08:37:26 +02:00
wilfriedrosetandAlexander Kukushkin 0136f252ab Add patronictl -k/--insecure flag and suport for restapi cert (#790)
Fixes https://github.com/zalando/patroni/issues/785
2018-08-29 16:08:13 +02:00
anikin-aaandAlexander Kukushkin 0e13677880 exclude members with nofailover tag (#798)
Exclude members with nofailover tag from `patronictl switchover/failover` output.
Fixes https://github.com/zalando/patroni/issues/769
2018-08-29 16:07:01 +02:00
anikin-aaandAlexander Kukushkin 68c0d87d42 check if output lines of controldata are possible to split (#797)
Otherwise it fails with scary stacktrace
2018-08-29 16:06:06 +02:00
Alexander KukushkinandGitHub 90cf930036 Refactor REST API health-checks (#779)
Make it more readable and easy to understand.
Mostly it is needed to implement https://github.com/zalando/patroni/issues/772
2018-08-29 11:35:22 +02:00
Jan MusslerandAlexander Kukushkin 2b87ae0cd0 Add member name to error message. (#792)
Analog to success message.
2018-08-29 11:30:51 +02:00
Alexander KukushkinandGitHub 5ca5dacaa9 Immediately reserve LSN on upon creation of replication slot (#783)
This feature is available starting from 9.6
2018-08-29 11:30:01 +02:00
Alexander KukushkinandGitHub 87e9aab04c Improve tests (#778)
* Implement missing unit-tests
* Add acceptance tests for ISSUE #776
* Update list of classifiers, keywords and authors
2018-08-29 11:29:37 +02:00
Alexander KukushkinandGitHub 518df2bc49 Search new sync candidate amoung potential and async standbys (#794)
In synchronos_mode_strict we put '*' into synchronos_standby_names, what makes one connection 'sync' and other connections 'potential'.
The code picking up the correct sync standby didn't consider 'potential' as a good candidate.

Fixes: https://github.com/zalando/patroni/issues/789
2018-08-29 11:28:46 +02:00
Alexander KukushkinandGitHub a513a7bb68 Improve stability of acceptance tests (#780)
last time tests were failing due to postgres/patroni slowness in picking sync standby
2018-08-29 11:13:18 +02:00
Alexander KukushkinandGitHub 715caaddf3 Remove .zappr.yaml (#795)
and switch to github approvals
2018-08-29 11:09:35 +02:00
Oleksii KliukinandAlexander Kukushkin b165183503 Reset is_leader status on demote (#777)
Make sure demoted cluster member stops responding with code 200 on the  /master API call.

Issue a new minor release.

Fixes https://github.com/zalando/patroni/issues/776
2018-08-14 17:08:08 +02:00
Dmitry DolgovandGitHub b282a0f254 Add "cluster_unlocked" field (#764)
Add a field to an api to figure out if a master is there from patroni point
of view. It can be useful, when you have an alert, based on Auto Scaling
Groups, and then ASG decided to shutdown the current master, spin up a
new instance but the current master shutdown is stuck. In this situation
the current master is no longer a part of ASG, but patroni and Postgres
are still alive on the instance, which means a new replica will not be
promoted yet - this will lead to a false alert, saying that your cluster
doesn't have any master node.
2018-08-13 14:02:01 +02:00
Alexander Kukushkin 5a56b71946 Add demo.sh script 2018-03-23 07:02:22 +01:00
Alexander Kukushkin e3b431bf38 Switch to endpoints and remove callback 2018-03-21 14:01:22 +01:00
36 changed files with 1025 additions and 244 deletions
-13
View File
@@ -1,13 +0,0 @@
# for github.com
approvals:
groups:
zalando:
minimum: 2
from:
orgs:
- "zalando"
# team should be valid team id in team service https://teams.auth.zalando.com/api/teams/:id
X-Zalando-Team: "acid"
# type should be one of [code, doc, config, tools, secrets]
# code will be the default value, if X-Zalando-Type is not found in .zappr.yml
X-Zalando-Type: code
+15
View File
@@ -25,6 +25,14 @@ Bootstrap configuration
- **use\_slots**: whether or not to use replication_slots. Must be False for PostgreSQL 9.3. You should comment out max_replication_slots before it becomes ineligible for leader status. - **use\_slots**: whether or not to use replication_slots. Must be False for PostgreSQL 9.3. You should comment out max_replication_slots before it becomes ineligible for leader status.
- **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower. - **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower.
- **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work. - **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work.
- **standby\_cluster**: if this section is defined, we want to bootstrap a standby cluster.
- **host**: an address of remote master
- **port**: a port of remote master
- **primary\_slot\_name**: which slot on the remote master to use for replication. This parameter is optional, the default value is derived from the instance name (see function `slot_name_from_member_name`).
- **create\_replica\_methods**: an ordered list of methods that can be used to bootstrap standby leader from the remote master, can be different from the list defined in :ref:`postgresql_settings`
- **restore\_command**: command to restore WAL records from the remote master to standby leader, can be different from the list defined in :ref:`postgresql_settings`
- **archive\_cleanup\_command**: cleanup command for standby leader
- **recovery\_min\_apply\_delay**: how long to wait before actually apply WAL records on a standby leader
- **method**: custom script to use for bootstrapping this cluster. - **method**: custom script to use for bootstrapping this cluster.
See :ref:`custom bootstrap methods documentation <custom_bootstrap>` for details. See :ref:`custom bootstrap methods documentation <custom_bootstrap>` for details.
When ``initdb`` is specified revert to the default ``initdb`` command. ``initdb`` is also triggered when no ``method`` When ``initdb`` is specified revert to the default ``initdb`` command. ``initdb`` is also triggered when no ``method``
@@ -146,6 +154,13 @@ REST API
- **certfile**: Specifies the file with the certificate in the PEM format. If the certfile is not specified or is left empty, the API server will work without SSL. - **certfile**: Specifies the file with the certificate in the PEM format. If the certfile is not specified or is left empty, the API server will work without SSL.
- **keyfile**: Specifies the file with the secret key in the PEM format. - **keyfile**: Specifies the file with the secret key in the PEM format.
CTL
---
- **Optional**:
- **insecure**: Allow connections to REST API without verifying SSL certs.
- **cacert**: Specifices the file with the CA_BUNDLE file or directory with certificates of trusted CAs to use while verifying REST API SSL certs.
- **certfile**: Specifies the file with the certificate in the PEM format to use while verifying REST API SSL certs. If not provided patronictl will use the value provided for REST API "certfile" parameter.
ZooKeeper ZooKeeper
---------- ----------
- **hosts**: list of ZooKeeper cluster members in format: ['host1:port1', 'host2:port2', 'etc...']. - **hosts**: list of ZooKeeper cluster members in format: ['host1:port1', 'host2:port2', 'etc...'].
+17
View File
@@ -3,6 +3,23 @@
Release notes Release notes
============= =============
Version 1.4.6
-------------
**Bug fixes and stability improvements**
This release fixes a critical issue with Patroni API /master endpoint returning 200 for the non-master node. This is a
reporting issue, no actual split-brain, but under certain circumstances clients might be directed to the read-only node.
- Reset is_leader status on demote (Alexander Kukushkin, Oleksii Kliukin)
Make sure demoted cluster member stops responding with code 200 on the /master API call.
- Add new "cluster_unlocked" field to the API output (Dmitry Dolgov)
This field indicates whether the cluster has the master running. It can be used when it is not possible to query any
other node but one of the replicas.
Version 1.4.5 Version 1.4.5
------------- -------------
+32
View File
@@ -129,3 +129,35 @@ and
- max-rate: '100M' - max-rate: '100M'
If all replica creation methods fail, Patroni will try again all methods in order during the next event loop cycle. If all replica creation methods fail, Patroni will try again all methods in order during the next event loop cycle.
Standby cluster
---------------
Another available option is to run a "standby cluster", that contains only of
standby nodes replicating from some remote master. This type of clusters has:
* "standby leader", that behaves pretty much like a regular cluster leader,
except it replicates from a remote master.
* cascade replicas, that are replicating from standby leader.
Standby leader holds and updates a leader lock in DCS. If the leader lock
expires, cascade replicas will perform an election to choose another leader
from the standbys. For the sake of flexibility, you can specify different
methods of creating a replica and recovery WAL records when a cluster is in the
"standby mode", and after it was detached to function as a normal cluster.
To configure such cluster you need to specify the section ``standby_cluster``
in a patroni configuration:
.. code:: YAML
bootstrap:
dcs:
standby_cluster:
host: 1.2.3.4
port: 5432
primary_slot_name: patroni
Note, that these options will be applied only once during cluster bootstrap,
and the only way to change them afterwards is through DCS.
+8 -6
View File
@@ -14,11 +14,13 @@ Feature: basic replication
Then table foo is present on postgres2 after 20 seconds Then table foo is present on postgres2 after 20 seconds
Scenario: check restart of sync replica Scenario: check restart of sync replica
Given I run patronictl.py restart batman postgres2 --force Given I shut down postgres2
And "sync" key in DCS has sync_standby=postgres1 after 2 seconds Then "sync" key in DCS has sync_standby=postgres1 after 5 seconds
And I run patronictl.py restart batman postgres1 --force When I start postgres2
Then I receive a response returncode 0 And I shut down postgres1
And "sync" key in DCS has sync_standby=postgres2 after 10 seconds Then "sync" key in DCS has sync_standby=postgres2 after 10 seconds
When I start postgres1
And "members/postgres1" key in DCS has state=running after 10 seconds
And I sleep for 2 seconds And I sleep for 2 seconds
When I issue a GET request to http://127.0.0.1:8010/sync When I issue a GET request to http://127.0.0.1:8010/sync
Then I receive a response code 200 Then I receive a response code 200
@@ -30,7 +32,7 @@ Feature: basic replication
Then I receive a response returncode 0 Then I receive a response returncode 0
When I sleep for 2 seconds When I sleep for 2 seconds
And I shut down postgres0 And I shut down postgres0
And I run patronictl.py resume batman And I run patronictl.py resume batman
Then I receive a response returncode 0 Then I receive a response returncode 0
And postgres2 role is the primary after 24 seconds And postgres2 role is the primary after 24 seconds
When I issue a PATCH request to http://127.0.0.1:8010/config with {"synchronous_mode": null, "master_start_timeout": 0} When I issue a PATCH request to http://127.0.0.1:8010/config with {"synchronous_mode": null, "master_start_timeout": 0}
+16
View File
@@ -71,6 +71,14 @@ Scenario: check the switchover via the API in the pause mode
And postgres1 role is the primary after 10 seconds And postgres1 role is the primary after 10 seconds
And postgres0 role is the secondary after 10 seconds And postgres0 role is the secondary after 10 seconds
And replication works from postgres1 to postgres0 after 20 seconds And replication works from postgres1 to postgres0 after 20 seconds
When I issue a GET request to http://127.0.0.1:8008/master
Then I receive a response code 503
When I issue a GET request to http://127.0.0.1:8008/replica
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8009/master
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8009/replica
Then I receive a response code 503
Scenario: check the scheduled switchover Scenario: check the scheduled switchover
Given I issue a scheduled switchover from postgres1 to postgres0 in 3 seconds Given I issue a scheduled switchover from postgres1 to postgres0 in 3 seconds
@@ -84,6 +92,14 @@ Scenario: check the scheduled switchover
And postgres0 role is the primary after 10 seconds And postgres0 role is the primary after 10 seconds
And postgres1 role is the secondary after 10 seconds And postgres1 role is the secondary after 10 seconds
And replication works from postgres0 to postgres1 after 25 seconds And replication works from postgres0 to postgres1 after 25 seconds
When I issue a GET request to http://127.0.0.1:8008/master
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8008/replica
Then I receive a response code 503
When I issue a GET request to http://127.0.0.1:8009/master
Then I receive a response code 503
When I issue a GET request to http://127.0.0.1:8009/replica
Then I receive a response code 200
Scenario: check the scheduled restart Scenario: check the scheduled restart
Given I issue a PATCH request to http://127.0.0.1:8008/config with {"postgresql": {"parameters": {"superuser_reserved_connections": "6"}}} Given I issue a PATCH request to http://127.0.0.1:8008/config with {"postgresql": {"parameters": {"superuser_reserved_connections": "6"}}}
+16
View File
@@ -0,0 +1,16 @@
Feature: standby cluster
Scenario: check replication of a single table in a standby cluster
Given I start postgres0 without slots sync
And I create a replication slot postgres1 on postgres0
And I start postgres1 in a standby cluster batman1 as a clone of postgres0
Then postgres1 is a leader of batman1 after 10 seconds
When I add the table foo to postgres0
Then table foo is present on postgres1 after 20 seconds
When I start postgres2 in a cluster batman1
Then postgres2 role is the replica after 24 seconds
And table foo is present on postgres2 after 20 seconds
Scenario: check failover
When I kill postgres1
Then postgres2 is replicating from postgres0 after 20 seconds
+78
View File
@@ -0,0 +1,78 @@
import time
from behave import step
select_replication_query = """
SELECT * FROM pg_catalog.pg_stat_replication
WHERE application_name = '{0}'
"""
create_replication_slot_query = """
SELECT pg_create_physical_replication_slot('{0}')
"""
@step('I start {name:w} without slots sync')
def start_patroni_without_slots_sync(context, name):
return context.pctl.start(name, custom_config={
"bootstrap": {
"dcs": {
"postgresql": {
"use_slots": False
}
}
}
})
@step('I start {name:w} in a cluster {cluster_name:w}')
def start_patroni(context, name, cluster_name):
return context.pctl.start(name, custom_config={
"scope": cluster_name
})
@step('I start {name:w} in a standby cluster {cluster_name:w} as a clone of {name2:w}')
def start_patroni_stanby_cluster(context, name, cluster_name, name2):
port = context.pctl._processes[name2]._connkwargs.get('port')
return context.pctl.start(name, custom_config={
"scope": cluster_name,
"bootstrap": {
"dcs": {
"standby_cluster": {
"host": "localhost",
"port": port,
"primary_slot_name": "postgres1",
}
}
}
})
@step('{pg_name1:w} is replicating from {pg_name2:w} after {timeout:d} seconds')
def check_replication_status(context, pg_name1, pg_name2, timeout):
bound_time = time.time() + timeout
while time.time() < bound_time:
cur = context.pctl.query(
pg_name2,
select_replication_query.format(pg_name1),
fail_ok=True
)
if cur and len(cur.fetchall()) != 0:
return True
time.sleep(1)
return False
@step('I create a replication slot {slot_name:w} on {pg_name:w}')
def create_replication_slot(context, slot_name, pg_name):
return context.pctl.query(
pg_name,
create_replication_slot_query.format(slot_name),
fail_ok=True
)
+7 -7
View File
@@ -1,29 +1,29 @@
FROM postgres:9.6 FROM postgres:10
MAINTAINER Alexander Kukushkin <[email protected]> MAINTAINER Alexander Kukushkin <[email protected]>
RUN export DEBIAN_FRONTEND=noninteractive \ RUN export DEBIAN_FRONTEND=noninteractive \
&& echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \ && echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \
&& apt-get update -y \ && apt-get update -y \
&& apt-get upgrade -y \ && apt-get upgrade -y \
&& apt-get install -y git curl jq python-psycopg2 python-yaml python-requests python-six python-pysocks \ && apt-get install -s patroni | sed -n -e '/^Inst patroni /d' -e 's/^Inst \([^ ]\+\) .*$/\1/p' \
python-dateutil python-pip python-prettytable python-wheel python-psutil python locales \ | xargs apt-get install -y curl jq locales git python3-pip python3-wheel \
## Make sure we have a en_US.UTF-8 locale available ## Make sure we have a en_US.UTF-8 locale available
&& localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \ && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \
&& pip install setuptools pip --upgrade \ && pip3 install setuptools \
&& pip install 'git+https://github.com/zalando/patroni.git#egg=patroni[kubernetes]' \ && pip3 install 'git+https://github.com/zalando/patroni.git#egg=patroni[kubernetes]' \
&& mkdir -p /home/postgres \ && mkdir -p /home/postgres \
&& chown postgres:postgres /home/postgres \ && chown postgres:postgres /home/postgres \
# Clean up # Clean up
&& apt-get remove -y git python-pip python-setuptools \ && apt-get remove -y git python3-pip python3-wheel \
&& apt-get autoremove -y \ && apt-get autoremove -y \
&& apt-get clean -y \ && apt-get clean -y \
&& rm -rf /var/lib/apt/lists/* /root/.cache && rm -rf /var/lib/apt/lists/* /root/.cache
ADD entrypoint.sh callback.py / ADD entrypoint.sh /
EXPOSE 5432 8008 EXPOSE 5432 8008
ENV LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ENV LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
-62
View File
@@ -1,62 +0,0 @@
#!/usr/bin/env python
import logging
import os
import socket
import sys
import time
from kubernetes import client as k8s_client, config as k8s_config
from urllib3.exceptions import HTTPError
from six.moves.http_client import HTTPException
logger = logging.getLogger(__name__)
class CoreV1Api(k8s_client.CoreV1Api):
def retry(func):
def wrapped(*args, **kwargs):
count = 0
while True:
try:
return func(*args, **kwargs)
except (HTTPException, HTTPError, socket.error, socket.timeout):
if count >= 10:
raise
logger.info('Throttling API requests...')
time.sleep(2 ** count * 0.5)
count += 1
return wrapped
@retry
def patch_namespaced_endpoints(self, *args, **kwargs):
return super(CoreV1Api, self).patch_namespaced_endpoints(*args, **kwargs)
def patch_master_endpoint(api, namespace, cluster):
addresses = [k8s_client.V1EndpointAddress(ip=os.environ['POD_IP'])]
ports = [k8s_client.V1EndpointPort(port=5432)]
subsets = [k8s_client.V1EndpointSubset(addresses=addresses, ports=ports)]
body = k8s_client.V1Endpoints(subsets=subsets)
return api.patch_namespaced_endpoints(cluster, namespace, body)
def main():
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)
if len(sys.argv) != 4 or sys.argv[1] not in ('on_start', 'on_stop', 'on_role_change'):
sys.exit('Usage: %s <action> <role> <cluster_name>', sys.argv[0])
action, role, cluster = sys.argv[1:4]
k8s_config.load_incluster_config()
k8s_api = CoreV1Api()
namespace = os.environ['KUBERNETES_NAMESPACE']
if role == 'master' and action in ('on_start', 'on_role_change'):
patch_master_endpoint(k8s_api, namespace, cluster)
if __name__ == '__main__':
main()
+189
View File
@@ -0,0 +1,189 @@
#!/bin/bash
# here you can defind your own alias to minikube
lkubectl='kubectl --context=local'
shopt -s expand_aliases
alias lkubectl="$lkubectl"
labels=application=patroni,cluster-name=patronidemo
# clean up objects from previous attempts
lkubectl delete statefulset,pods,service,endpoints -l $labels
# clear old panes
for pane in {3..1}; do
tmux send-keys -t 0.$pane C-c
tmux kill-pane -t 0.$pane
done
tmux send-keys -t 0.0 C-c
tmux send-keys -t 0.0 C-l
# split window into 3 panes
tmux split-window -h -t 0.0
tmux split-window -v -t 0.0
tmux split-window -v -t 0.1
tmux send-keys -t 0.3 "export PGPASSWORD=zalando" Enter
tmux send-keys -t 0.3 "export PGCONNECT_TIMEOUT=1" Enter
for pane in {0..3}; do
tmux send-keys -t 0.$pane "shopt -s expand_aliases" Enter
tmux send-keys -t 0.$pane "alias lkubectl='$lkubectl'" Enter
tmux send-keys -t 0.$pane C-l
done
# run
tmux resize-pane -Z -t 0.3
tmux send-keys -t 0.3 "lkubectl apply -f patroni_k8s.yaml" Enter
tmux send-keys -t 0.3 "lkubectl get pods -w -l $labels -L role -o wide" Enter
read
tmux send-keys -t 0.3 C-c
#tmux send-keys -t 0.3 C-l
#
#tmux send-keys -t 0.3 "lkubectl get pods -l $labels -L role -o wide" Enter
#
#read
# tail logs from patroni pods
for pane in {0..2}; do
tmux send-keys -t 0.$pane "lkubectl logs patronidemo-$pane -f" Enter
done
tmux resize-pane -Z -t 0.3
read
tmux resize-pane -Z -t 0.0
read
tmux resize-pane -Z -t 0.0
read
tmux resize-pane -Z -t 0.1
read
tmux resize-pane -Z -t 0.1
read
tmux resize-pane -Z -t 0.3
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl get pods -l $labels -L role -o wide" Enter
read
tmux send-keys -t 0.3 Enter
tmux send-keys -t 0.3 "lkubectl get services -l $labels" Enter
read
tmux send-keys -t 0.3 Enter
tmux send-keys -t 0.3 "lkubectl get endpoints -l $labels" Enter
read
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl get pods -l $labels -L role -o wide" Enter
tmux send-keys -t 0.3 Enter
tmux send-keys -t 0.3 "lkubectl get endpoints patronidemo -o yaml" Enter
read
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl get pods -l $labels -L role -o wide" Enter
tmux send-keys -t 0.3 Enter
tmux send-keys -t 0.3 "lkubectl describe service patronidemo-repl" Enter
read
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl get endpoints patronidemo-config -o yaml" Enter
read
MASTERIP=$(lkubectl get service patronidemo -o jsonpath='{.spec.clusterIP}')
tmux resize-pane -Z -t 0.3
tmux send-keys -t 0.3 "watch -n 1 \"psql -h $MASTERIP -U postgres -c \\\"select txid_current(), array_agg(application_name||'=>'|| sync_state) AS \\\\\\\"array_agg(application_name||'=>'||sync_state)\\\\\\\" from pg_stat_replication\\\"\"" Enter
read
# kill master node
lkubectl delete pod patronidemo-0
read
tmux resize-pane -Z -t 0.1
tmux send-keys -t 0.1 C-b PageUp
read
tmux send-keys -t 0.1 Enter
tmux resize-pane -Z -t 0.1
read
tmux resize-pane -Z -t 0.2
tmux send-keys -t 0.2 PageUp
read
tmux send-keys -t 0.2 Enter
tmux resize-pane -Z -t 0.2
read
tmux send-keys -t 0.0 C-c
tmux send-keys -t 0.0 "lkubectl logs patronidemo-0 -f" Enter
read
tmux resize-pane -Z -t 0.3
tmux send-keys -t 0.3 C-c
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl get pods -l $labels -L role -o wide" Enter
tmux send-keys -t 0.3 Enter
tmux send-keys -t 0.3 "lkubectl get endpoints -l $labels" Enter
read
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl get endpoints patronidemo -o yaml" Enter
read
tmux resize-pane -Z -t 0.3
tmux send-keys -t 0.3 C-c
tmux send-keys -t 0.3 C-l
tmux send-keys -t 0.3 "lkubectl exec -ti patronidemo-0 patronictl switchover patronidemo" Enter
read
tmux send-keys -t 0.3 Enter
read
tmux send-keys -t 0.3 "patronidemo-0" Enter
read
tmux send-keys -t 0.3 Enter
read
tmux send-keys -t 0.3 "y" Enter
read
tmux send-keys -t 0.3 "lkubectl exec -ti patronidemo-0 patronictl list patronidemo" Enter
+4 -17
View File
@@ -13,24 +13,11 @@ bootstrap:
- data-checksums - data-checksums
pg_hba: pg_hba:
- host all all 0.0.0.0/0 md5 - host all all 0.0.0.0/0 md5
- host replication ${PATRONI_REPLICATION_USERNAME} ${POD_IP}/16 md5 - host replication ${PATRONI_REPLICATION_USERNAME} ${PATRONI_KUBERNETES_POD_IP}/16 md5
restapi: restapi:
connect_address: '${POD_IP}:8008' connect_address: '${PATRONI_KUBERNETES_POD_IP}:8008'
postgresql: postgresql:
connect_address: '${POD_IP}:5432' connect_address: '${PATRONI_KUBERNETES_POD_IP}:5432'
authentication:
superuser:
password: '${PATRONI_SUPERUSER_PASSWORD}'
replication:
password: '${PATRONI_REPLICATION_PASSWORD}'
callbacks:
on_start: /callback.py
on_stop: /callback.py
on_role_change: /callback.py
__EOF__ __EOF__
unset PATRONI_SUPERUSER_PASSWORD PATRONI_REPLICATION_PASSWORD exec /usr/bin/python3 /usr/local/bin/patroni /home/postgres/patroni.yml
export KUBERNETES_NAMESPACE=$PATRONI_KUBERNETES_NAMESPACE
export POD_NAME=$PATRONI_NAME
exec /usr/bin/python /usr/local/bin/patroni /home/postgres/patroni.yml
+30 -1
View File
@@ -1,3 +1,5 @@
# This manifest (and Docker image) works only with emptyDir volume and are designed for demo purpose.
# For production usage please take a look at https://github.com/zalando/spilo/tree/master/postgres-appliance
apiVersion: apps/v1beta1 apiVersion: apps/v1beta1
kind: StatefulSet kind: StatefulSet
metadata: metadata:
@@ -19,6 +21,9 @@ spec:
- name: *cluster_name - name: *cluster_name
image: patroni # docker build -t patroni . image: patroni # docker build -t patroni .
imagePullPolicy: IfNotPresent imagePullPolicy: IfNotPresent
# resources:
# limits:
# cpu: 100m
ports: ports:
- containerPort: 8008 - containerPort: 8008
protocol: TCP protocol: TCP
@@ -28,7 +33,7 @@ spec:
- mountPath: /home/postgres/pgdata - mountPath: /home/postgres/pgdata
name: pgdata name: pgdata
env: env:
- name: POD_IP - name: PATRONI_KUBERNETES_POD_IP
valueFrom: valueFrom:
fieldRef: fieldRef:
fieldPath: status.podIP fieldPath: status.podIP
@@ -36,6 +41,8 @@ spec:
valueFrom: valueFrom:
fieldRef: fieldRef:
fieldPath: metadata.namespace fieldPath: metadata.namespace
- name: PATRONI_KUBERNETES_USE_ENDPOINTS
value: 'true'
- name: PATRONI_KUBERNETES_LABELS - name: PATRONI_KUBERNETES_LABELS
value: '{application: patroni, cluster-name: patronidemo}' value: '{application: patroni, cluster-name: patronidemo}'
- name: PATRONI_SUPERUSER_USERNAME - name: PATRONI_SUPERUSER_USERNAME
@@ -86,6 +93,7 @@ spec:
# storage: 5Gi # storage: 5Gi
--- ---
# Endpoint for leader elections
apiVersion: v1 apiVersion: v1
kind: Endpoints kind: Endpoints
metadata: metadata:
@@ -96,6 +104,7 @@ metadata:
subsets: [] subsets: []
--- ---
# master Service
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
metadata: metadata:
@@ -110,6 +119,26 @@ spec:
targetPort: 5432 targetPort: 5432
--- ---
# replica Service
apiVersion: v1
kind: Service
metadata:
name: patronidemo-repl
labels:
application: patroni
cluster-name: &cluster_name patronidemo
spec:
type: ClusterIP
selector:
application: patroni
cluster-name: *cluster_name
role: replica
ports:
- port: 5432
targetPort: 5432
---
# Secrets (superuser password and replication passwor)
apiVersion: v1 apiVersion: v1
kind: Secret kind: Secret
metadata: metadata:
+1 -1
View File
@@ -188,7 +188,7 @@ def main():
if ret == (0, 0): if ret == (0, 0):
break break
elif ret[0] != pid: elif ret[0] != pid:
logging.info('Reaped pid=%s, exit status=%s', *ret) logger.info('Reaped pid=%s, exit status=%s', *ret)
except OSError: except OSError:
pass pass
+16 -29
View File
@@ -84,35 +84,20 @@ class RestApiHandler(BaseHTTPRequestHandler):
patroni = self.server.patroni patroni = self.server.patroni
cluster = patroni.dcs.cluster cluster = patroni.dcs.cluster
def is_synchronous(): replica_status_code = 200 if not patroni.noloadbalance and response.get('role') == 'replica' else 503
return (cluster.is_synchronous_mode() and cluster.sync status_code = 503
and cluster.sync.sync_standby == patroni.postgresql.name)
def is_balanceable_replica(): if 'master' in path:
return response.get('role') == 'replica' and not patroni.noloadbalance status_code = 200 if patroni.ha.is_leader() else 503
elif 'replica' in path:
if cluster: # dcs available status_code = replica_status_code
if patroni.ha.is_leader(): elif cluster: # dcs is available
status_code = 200 if 'master' in path else 503 is_synchronous = cluster.is_synchronous_mode() and cluster.sync \
elif 'role' not in response: and cluster.sync.sync_standby == patroni.postgresql.name
status_code = 503 if path in ('/sync', '/synchronous') and is_synchronous:
elif response['role'] == 'master': # running as master but without leader lock!!!! status_code = replica_status_code
status_code = 503 elif path in ('/async', '/asynchronous') and not is_synchronous:
elif path in ('/sync', '/synchronous'): status_code = replica_status_code
status_code = 200 if is_balanceable_replica() and is_synchronous() else 503
elif path in ('/async', '/asynchronous'):
status_code = 200 if is_balanceable_replica() and not is_synchronous() else 503
elif response['role'] in path: # response['role'] != 'master'
status_code = 503 if patroni.noloadbalance else 200
else:
status_code = 503
elif 'role' in response and response['role'] in path:
status_code = 503 if response['role'] != 'master' and patroni.noloadbalance else 200
elif patroni.ha.restart_scheduled() and patroni.postgresql.role == 'master' and 'master' in path:
# exceptional case for master node when the postgres is being restarted via API
status_code = 200
else:
status_code = 503
if write_status_code_only: # when haproxy sends OPTIONS request it reads only status code and nothing more if write_status_code_only: # when haproxy sends OPTIONS request it reads only status code and nothing more
message = self.responses[status_code][0] message = self.responses[status_code][0]
@@ -415,6 +400,8 @@ class RestApiHandler(BaseHTTPRequestHandler):
def get_postgresql_status(self, retry=False): def get_postgresql_status(self, retry=False):
try: try:
cluster = self.server.patroni.dcs.cluster
if self.server.patroni.postgresql.state not in ('running', 'restarting', 'starting'): if self.server.patroni.postgresql.state not in ('running', 'restarting', 'starting'):
raise RetryFailedError('') raise RetryFailedError('')
stmt = ("WITH replication_info AS (" stmt = ("WITH replication_info AS ("
@@ -439,6 +426,7 @@ class RestApiHandler(BaseHTTPRequestHandler):
'postmaster_start_time': row[0], 'postmaster_start_time': row[0],
'role': 'replica' if row[1] == 0 else 'master', 'role': 'replica' if row[1] == 0 else 'master',
'server_version': self.server.patroni.postgresql.server_version, 'server_version': self.server.patroni.postgresql.server_version,
'cluster_unlocked': bool(not cluster or cluster.is_unlocked()),
'xlog': ({ 'xlog': ({
'received_location': row[3], 'received_location': row[3],
'replayed_location': row[4], 'replayed_location': row[4],
@@ -451,7 +439,6 @@ class RestApiHandler(BaseHTTPRequestHandler):
if row[1] > 0: if row[1] > 0:
result['timeline'] = row[1] result['timeline'] = row[1]
else: else:
cluster = self.server.patroni.dcs.cluster
leader_timeline = None if not cluster or cluster.is_unlocked() else cluster.leader.timeline leader_timeline = None if not cluster or cluster.is_unlocked() else cluster.leader.timeline
result['timeline'] = self.server.patroni.postgresql.replica_cached_timeline(leader_timeline) result['timeline'] = self.server.patroni.postgresql.replica_cached_timeline(leader_timeline)
+31 -3
View File
@@ -1,13 +1,14 @@
import json import json
import logging import logging
import os import os
import six
import sys import sys
import tempfile import tempfile
import yaml import yaml
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
from patroni.dcs import ClusterConfig from patroni.dcs import ClusterConfig, is_standby_cluster
from patroni.postgresql import Postgresql from patroni.postgresql import Postgresql
from patroni.utils import deep_compare, parse_bool, parse_int, patch_config from patroni.utils import deep_compare, parse_bool, parse_int, patch_config
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
@@ -45,6 +46,15 @@ class Config(object):
'master_start_timeout': 300, 'master_start_timeout': 300,
'synchronous_mode': False, 'synchronous_mode': False,
'synchronous_mode_strict': False, 'synchronous_mode_strict': False,
'standby_cluster': {
'create_replica_methods': '',
'host': '',
'port': '',
'primary_slot_name': '',
'restore_command': '',
'archive_cleanup_command': '',
'recovery_min_apply_delay': ''
},
'postgresql': { 'postgresql': {
'bin_dir': '', 'bin_dir': '',
'use_slots': True, 'use_slots': True,
@@ -88,6 +98,10 @@ class Config(object):
def dynamic_configuration(self): def dynamic_configuration(self):
return deepcopy(self._dynamic_configuration) return deepcopy(self._dynamic_configuration)
@property
def is_standby_cluster(self):
return is_standby_cluster(self._dynamic_configuration.get('standby_cluster'))
def check_mode(self, mode): def check_mode(self, mode):
return bool(parse_bool(self._dynamic_configuration.get(mode))) return bool(parse_bool(self._dynamic_configuration.get(mode)))
@@ -183,6 +197,13 @@ class Config(object):
config['postgresql'][name].update(self._process_postgresql_parameters(value)) config['postgresql'][name].update(self._process_postgresql_parameters(value))
elif name not in ('connect_address', 'listen', 'data_dir', 'pgpass', 'authentication'): elif name not in ('connect_address', 'listen', 'data_dir', 'pgpass', 'authentication'):
config['postgresql'][name] = deepcopy(value) config['postgresql'][name] = deepcopy(value)
elif name == 'standby_cluster':
allowed_keys = self.__DEFAULT_CONFIG['standby_cluster'].keys()
expected = {
k: v for k, v in (value or {}).items()
if (k in allowed_keys and isinstance(v, six.string_types))
}
config['standby_cluster'].update(expected)
elif name in config: # only variables present in __DEFAULT_CONFIG allowed to be overriden from DCS elif name in config: # only variables present in __DEFAULT_CONFIG allowed to be overriden from DCS
if name in ('synchronous_mode', 'synchronous_mode_strict'): if name in ('synchronous_mode', 'synchronous_mode_strict'):
config[name] = value config[name] = value
@@ -317,8 +338,15 @@ class Config(object):
if 'name' not in config and 'name' in pg_config: if 'name' not in config and 'name' in pg_config:
config['name'] = pg_config['name'] config['name'] = pg_config['name']
pg_config.update({p: config[p] for p in ('name', 'scope', 'retry_timeout', updated_fields = (
'synchronous_mode', 'maximum_lag_on_failover') if p in config}) 'name',
'scope',
'retry_timeout',
'synchronous_mode',
'maximum_lag_on_failover'
)
pg_config.update({p: config[p] for p in updated_fields if p in config})
return config return config
+25 -4
View File
@@ -103,15 +103,20 @@ option_watch = click.option('-W', is_flag=True, help='Auto update the screen eve
option_force = click.option('--force', is_flag=True, help='Do not ask for confirmation at any point') option_force = click.option('--force', is_flag=True, help='Do not ask for confirmation at any point')
arg_cluster_name = click.argument('cluster_name', required=False, arg_cluster_name = click.argument('cluster_name', required=False,
default=lambda: click.get_current_context().obj.get('scope')) default=lambda: click.get_current_context().obj.get('scope'))
option_insecure = click.option('-k', '--insecure', is_flag=True, help='Allow connections to SSL sites without certs')
@click.group() @click.group()
@click.option('--config-file', '-c', help='Configuration file', default=CONFIG_FILE_PATH) @click.option('--config-file', '-c', help='Configuration file', default=CONFIG_FILE_PATH)
@click.option('--dcs', '-d', help='Use this DCS', envvar='DCS') @click.option('--dcs', '-d', help='Use this DCS', envvar='DCS')
@option_insecure
@click.pass_context @click.pass_context
def ctl(ctx, config_file, dcs): def ctl(ctx, config_file, dcs, insecure):
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=os.environ.get('LOGLEVEL', 'WARNING')) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=os.environ.get('LOGLEVEL', 'WARNING'))
logging.captureWarnings(True) # Capture eventual SSL warning
ctx.obj = load_config(config_file, dcs) ctx.obj = load_config(config_file, dcs)
# backward compatibility for configuration file where ctl section is not define
ctx.obj.setdefault('ctl', {})['insecure'] = ctx.obj.get('ctl', {}).get('insecure') or insecure
def get_dcs(config, scope): def get_dcs(config, scope):
@@ -129,6 +134,7 @@ def auth_header(config):
def request_patroni(member, request_type, endpoint, content=None, headers=None): def request_patroni(member, request_type, endpoint, content=None, headers=None):
ctx = click.get_current_context() # the current click context
headers = headers or {} headers = headers or {}
url_parts = urlparse(member.api_url) url_parts = urlparse(member.api_url)
logging.debug(url_parts) logging.debug(url_parts)
@@ -137,8 +143,21 @@ def request_patroni(member, request_type, endpoint, content=None, headers=None):
url = '{0}://{1}/{2}'.format(url_parts.scheme, url_parts.netloc, endpoint) url = '{0}://{1}/{2}'.format(url_parts.scheme, url_parts.netloc, endpoint)
insecure = ctx.obj.get('ctl', {}).get('insecure', False)
# Get certfile if any from several configuration namespace
cert = ctx.obj.get('ctl', {}).get('cacert') or \
ctx.obj.get('restapi', {}).get('cacert') or \
ctx.obj.get('restapi', {}).get('certfile')
# In the case we specificaly disable SSL cert verification we don't want to have the warning
if insecure:
verify = False
elif cert:
verify = cert
else:
verify = True
return getattr(requests, request_type)(url, headers=headers, return getattr(requests, request_type)(url, headers=headers,
data=json.dumps(content) if content else None, timeout=60) data=json.dumps(content) if content else None, timeout=60,
verify=verify)
def print_output(columns, rows=None, alignment=None, fmt='pretty', header=True, delimiter='\t'): def print_output(columns, rows=None, alignment=None, fmt='pretty', header=True, delimiter='\t'):
@@ -585,7 +604,8 @@ def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, for
if master is not None and cluster.leader and cluster.leader.member.name != master: if master is not None and cluster.leader and cluster.leader.member.name != master:
raise PatroniCtlException('Member {0} is not the leader of cluster {1}'.format(master, cluster_name)) raise PatroniCtlException('Member {0} is not the leader of cluster {1}'.format(master, cluster_name))
candidate_names = [str(m.name) for m in cluster.members if m.name != master] # excluding members with nofailover tag
candidate_names = [str(m.name) for m in cluster.members if m.name != master and not m.nofailover]
# We sort the names for consistent output to the client # We sort the names for consistent output to the client
candidate_names.sort() candidate_names.sort()
@@ -902,7 +922,8 @@ def toggle_pause(config, cluster_name, paused, wait):
for member in members: for member in members:
try: try:
r = request_patroni(member, 'patch', 'config', {'pause': paused or None}, auth_header(config)) r = request_patroni(member, 'patch', 'config', {'pause': paused or None}, auth_header(config))
except Exception: except Exception as err:
logging.warning(str(err))
logging.warning('Member %s is not accessible', member.name) logging.warning('Member %s is not accessible', member.name)
continue continue
+54 -2
View File
@@ -108,12 +108,29 @@ class Member(namedtuple('Member', 'index,name,session,data')):
@property @property
def conn_url(self): def conn_url(self):
return self.data.get('conn_url') conn_url = self.data.get('conn_url')
conn_kwargs = self.data.get('conn_kwargs')
if conn_url:
return conn_url
if conn_kwargs:
conn_url = 'postgresql://{host}:{port}'.format(
host=conn_kwargs.get('host'),
port=conn_kwargs.get('port'),
)
self.data['conn_url'] = conn_url
return conn_url
def conn_kwargs(self, auth=None): def conn_kwargs(self, auth=None):
defaults = {
"host": "",
"port": "",
"database": ""
}
ret = self.data.get('conn_kwargs') ret = self.data.get('conn_kwargs')
if ret: if ret:
ret = ret.copy() defaults.update(ret)
ret = defaults
else: else:
r = urlparse(self.conn_url) r = urlparse(self.conn_url)
ret = { ret = {
@@ -159,6 +176,27 @@ class Member(namedtuple('Member', 'index,name,session,data')):
return self.state == 'running' return self.state == 'running'
class RemoteMember(Member):
""" Represents a remote master for a standby cluster
"""
def __new__(cls, name, data):
return super(RemoteMember, cls).__new__(cls, None, name, None, data)
@staticmethod
def allowed_keys():
return ('primary_slot_name',
'create_replica_methods',
'restore_command',
'archive_cleanup_command',
'recovery_min_apply_delay')
def __getattr__(self, name):
if name not in RemoteMember.allowed_keys():
return
return self.data.get(name)
class Leader(namedtuple('Leader', 'index,session,member')): class Leader(namedtuple('Leader', 'index,session,member')):
"""Immutable object (namedtuple) which represents leader key. """Immutable object (namedtuple) which represents leader key.
@@ -359,6 +397,9 @@ class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operat
def is_synchronous_mode(self): def is_synchronous_mode(self):
return self.check_mode('synchronous_mode') return self.check_mode('synchronous_mode')
def is_standby_cluster(self):
return is_standby_cluster(self.config and self.config.data.get('standby_cluster'))
@six.add_metaclass(abc.ABCMeta) @six.add_metaclass(abc.ABCMeta)
class AbstractDCS(object): class AbstractDCS(object):
@@ -612,3 +653,14 @@ class AbstractDCS(object):
self.event.wait(timeout) self.event.wait(timeout)
return self.event.isSet() return self.event.isSet()
def is_standby_cluster(config):
""" Check whether or not provided configuration describes a standby cluster.
Config can be both patroni config or cluster.config.data
"""
return isinstance(config, dict) and (
config.get('host') or
config.get('port') or
config.get('restore_command')
)
+91 -5
View File
@@ -2,6 +2,7 @@ from __future__ import absolute_import
import json import json
import logging import logging
import os import os
import re
import socket import socket
import ssl import ssl
import time import time
@@ -12,7 +13,7 @@ from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, M
from patroni.exceptions import DCSError from patroni.exceptions import DCSError
from patroni.utils import deep_compare, parse_bool, Retry, RetryFailedError, split_host_port from patroni.utils import deep_compare, parse_bool, Retry, RetryFailedError, split_host_port
from urllib3.exceptions import HTTPError from urllib3.exceptions import HTTPError
from six.moves.urllib.parse import urlencode, urlparse from six.moves.urllib.parse import urlencode, urlparse, quote
from six.moves.http_client import HTTPException from six.moves.http_client import HTTPException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -133,6 +134,31 @@ def catch_consul_errors(func):
return wrapper return wrapper
def force_if_last_failed(func):
def wrapper(*args, **kwargs):
if wrapper.last_result is False:
kwargs['force'] = True
wrapper.last_result = func(*args, **kwargs)
return wrapper.last_result
wrapper.last_result = None
return wrapper
def service_name_from_scope_name(scope_name):
"""Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul')
"""
def replace_char(match):
c = match.group(0)
return '-' if c in '. _' else "u{:04d}".format(ord(c))
service_name = re.sub(r'[^a-z0-9\-]', replace_char, scope_name.lower())
return service_name[0:230]
class Consul(AbstractDCS): class Consul(AbstractDCS):
def __init__(self, config): def __init__(self, config):
@@ -144,7 +170,6 @@ class Consul(AbstractDCS):
retry_exceptions=(ConsulInternalError, HTTPException, retry_exceptions=(ConsulInternalError, HTTPException,
HTTPError, socket.error, socket.timeout)) HTTPError, socket.error, socket.timeout))
self._my_member_data = {}
kwargs = {} kwargs = {}
if 'url' in config: if 'url' in config:
r = urlparse(config['url']) r = urlparse(config['url'])
@@ -175,6 +200,13 @@ class Consul(AbstractDCS):
self.set_ttl(config.get('ttl') or 30) self.set_ttl(config.get('ttl') or 30)
self._last_session_refresh = 0 self._last_session_refresh = 0
self.__session_checks = config.get('checks') self.__session_checks = config.get('checks')
self._register_service = config.get('register_service', False)
if self._register_service:
self._service_name = service_name_from_scope_name(self._scope)
if self._scope != self._service_name:
logger.warning('Using %s as consul service name instead of scope name %s', self._service_name,
self._scope)
self._service_check_interval = config.get('service_check_interval', '5s')
if not self._ctl: if not self._ctl:
self.create_session() self.create_session()
@@ -318,18 +350,71 @@ class Consul(AbstractDCS):
except Exception: except Exception:
return False return False
if not create_member and member and deep_compare(data, self._my_member_data): if not create_member and member and deep_compare(data, member.data):
return True return True
try: try:
args = {} if permanent else {'acquire': self._session} args = {} if permanent else {'acquire': self._session}
self._client.kv.put(self.member_path, json.dumps(data, separators=(',', ':')), **args) self._client.kv.put(self.member_path, json.dumps(data, separators=(',', ':')), **args)
self._my_member_data = data if self._register_service:
self.update_service(not create_member and member and member.data or {}, data)
return True return True
except Exception: except Exception:
logger.exception('touch_member') logger.exception('touch_member')
return False return False
@catch_consul_errors
def register_service(self, service_name, **kwargs):
logger.info('Register service %s, params %s', service_name, kwargs)
return self._client.agent.service.register(service_name, **kwargs)
@catch_consul_errors
def deregister_service(self, service_id):
logger.info('Deregister service %s', service_id)
# service_id can contain special characters, but is used as part of uri in deregister request
service_id = quote(service_id)
return self._client.agent.service.deregister(service_id)
def _update_service(self, data):
service_name = self._service_name
role = data['role']
state = data['state']
api_parts = urlparse(data['api_url'])
api_parts = api_parts._replace(path='/{0}'.format(role))
conn_parts = urlparse(data['conn_url'])
check = base.Check.http(api_parts.geturl(), self._service_check_interval, deregister=self._client.http.ttl * 10)
params = {
'service_id': '{0}/{1}'.format(self._scope, self._name),
'address': conn_parts.hostname,
'port': conn_parts.port,
'check': check,
'tags': [role]
}
if state == 'stopped':
return self.deregister_service(params['service_id'])
if role in ['master', 'replica']:
if state != 'running':
return
return self.register_service(service_name, **params)
logger.warning('Could not register service: unknown role type %s', role)
@force_if_last_failed
def update_service(self, old_data, new_data, force=False):
update = False
for key in ['role', 'api_url', 'conn_url', 'state']:
if key not in new_data:
logger.warning('Could not register service: not enough params in member data')
return
if old_data.get(key) != new_data[key]:
update = True
if force or update:
return self._update_service(new_data)
@catch_consul_errors @catch_consul_errors
def _do_attempt_to_acquire_leader(self, kwargs): def _do_attempt_to_acquire_leader(self, kwargs):
return self.retry(self._client.kv.put, self.leader_path, self._name, **kwargs) return self.retry(self._client.kv.put, self.leader_path, self._name, **kwargs)
@@ -341,6 +426,7 @@ class Consul(AbstractDCS):
ret = self._do_attempt_to_acquire_leader({} if permanent else {'acquire': self._session}) ret = self._do_attempt_to_acquire_leader({} if permanent else {'acquire': self._session})
if not ret: if not ret:
logger.info('Could not take out TTL lock') logger.info('Could not take out TTL lock')
return ret return ret
def take_leader(self): def take_leader(self):
@@ -408,7 +494,7 @@ class Consul(AbstractDCS):
idx, _ = self._client.kv.get(self.leader_path, index=leader_index, wait=str(timeout) + 's') idx, _ = self._client.kv.get(self.leader_path, index=leader_index, wait=str(timeout) + 's')
return str(idx) != str(leader_index) return str(idx) != str(leader_index)
except (ConsulException, HTTPException, HTTPError, socket.error, socket.timeout): except (ConsulException, HTTPException, HTTPError, socket.error, socket.timeout):
logging.exception('watch') logger.exception('watch')
timeout = end_time - time.time() timeout = end_time - time.time()
+1 -1
View File
@@ -496,7 +496,7 @@ class Etcd(AbstractDCS):
@catch_etcd_errors @catch_etcd_errors
def touch_member(self, data, ttl=None, permanent=False): def touch_member(self, data, ttl=None, permanent=False):
data = json.dumps(data, separators=(',', ':')) data = json.dumps(data, separators=(',', ':'))
return self.retry(self._client.set, self.member_path, data, None if permanent else ttl or self._ttl) return self._client.set(self.member_path, data, None if permanent else ttl or self._ttl)
@catch_etcd_errors @catch_etcd_errors
def take_leader(self): def take_leader(self):
+1 -1
View File
@@ -399,7 +399,7 @@ class Kubernetes(AbstractDCS):
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
except Exception: except Exception:
logging.exception('watch') logger.exception('watch')
timeout = end_time - time.time() timeout = end_time - time.time()
+31 -43
View File
@@ -59,7 +59,6 @@ class ZooKeeper(AbstractDCS):
max_delay=1, max_tries=-1, sleep_func=time.sleep)) max_delay=1, max_tries=-1, sleep_func=time.sleep))
self._client.add_listener(self.session_listener) self._client.add_listener(self.session_listener)
self._my_member_data = {}
self._fetch_cluster = True self._fetch_cluster = True
self._orig_kazoo_connect = self._client._connection._connect self._orig_kazoo_connect = self._client._connection._connect
@@ -208,45 +207,52 @@ class ZooKeeper(AbstractDCS):
self.cluster_watcher(None) self.cluster_watcher(None)
raise ZooKeeperError('ZooKeeper in not responding properly') raise ZooKeeperError('ZooKeeper in not responding properly')
def _create(self, path, value, **kwargs): def _create(self, path, value, retry=False, ephemeral=False):
try: try:
self._client.retry(self._client.create, path, value.encode('utf-8'), **kwargs) if retry:
self._client.retry(self._client.create, path, value, makepath=True, ephemeral=ephemeral)
else:
self._client.create_async(path, value, makepath=True, ephemeral=ephemeral).get(timeout=1)
return True return True
except Exception: except Exception:
return False logger.exception('Failed to create %s', path)
return False
def attempt_to_acquire_leader(self, permanent=False): def attempt_to_acquire_leader(self, permanent=False):
ret = self._create(self.leader_path, self._name, makepath=True, ephemeral=not permanent) ret = self._create(self.leader_path, self._name.encode('utf-8'), retry=True, ephemeral=not permanent)
if not ret: if not ret:
logger.info('Could not take out TTL lock') logger.info('Could not take out TTL lock')
return ret return ret
def __set_failover_or_sync_state_value(self, key, value, index=None): def _set_or_create(self, key, value, index=None, retry=False, do_not_create_empty=False):
value = value.encode('utf-8')
try: try:
self._client.retry(self._client.set, key, value.encode('utf-8'), version=index or -1) if retry:
self._client.retry(self._client.set, key, value, version=index or -1)
else:
self._client.set_async(key, value, version=index or -1).get(timeout=1)
return True return True
except NoNodeError: except NoNodeError:
return value == '' or (index is None and self._create(key, value)) if do_not_create_empty and not value:
return True
elif index is None:
return self._create(key, value, retry)
else:
return False
except Exception: except Exception:
logging.exception('set_failover_value') logger.exception('Failed to update %s', key)
return False return False
def set_failover_value(self, value, index=None): def set_failover_value(self, value, index=None):
return self.__set_failover_or_sync_state_value(self.failover_path, value, index) return self._set_or_create(self.failover_path, value, index)
def set_config_value(self, value, index=None): def set_config_value(self, value, index=None):
try: return self._set_or_create(self.config_path, value, index, retry=True)
self._client.retry(self._client.set, self.config_path, value.encode('utf-8'), version=index or -1)
return True
except NoNodeError:
return index is None and self._create(self.config_path, value)
except Exception:
logging.exception('set_config_value')
return False
def initialize(self, create_new=True, sysid=""): def initialize(self, create_new=True, sysid=""):
return self._create(self.initialize_path, sysid, makepath=True) if create_new \ sysid = sysid.encode('utf-8')
else self._client.retry(self._client.set, self.initialize_path, sysid.encode("utf-8")) return self._create(self.initialize_path, sysid, retry=True) if create_new \
else self._client.retry(self._client.set, self.initialize_path, sysid)
def touch_member(self, data, ttl=None, permanent=False): def touch_member(self, data, ttl=None, permanent=False):
cluster = self.cluster cluster = self.cluster
@@ -262,13 +268,12 @@ class ZooKeeper(AbstractDCS):
member = None member = None
if member: if member:
if deep_compare(data, self._my_member_data): if deep_compare(data, member.data):
return True return True
else: else:
try: try:
self._client.create_async(self.member_path, encoded_data, makepath=True, self._client.create_async(self.member_path, encoded_data, makepath=True,
ephemeral=not permanent).get(timeout=1) ephemeral=not permanent).get(timeout=1)
self._my_member_data = data
return True return True
except Exception as e: except Exception as e:
if not isinstance(e, NodeExistsError): if not isinstance(e, NodeExistsError):
@@ -276,7 +281,6 @@ class ZooKeeper(AbstractDCS):
return False return False
try: try:
self._client.set_async(self.member_path, encoded_data).get(timeout=1) self._client.set_async(self.member_path, encoded_data).get(timeout=1)
self._my_member_data = data
return True return True
except Exception: except Exception:
logger.exception('touch_member') logger.exception('touch_member')
@@ -286,30 +290,14 @@ class ZooKeeper(AbstractDCS):
def take_leader(self): def take_leader(self):
return self.attempt_to_acquire_leader() return self.attempt_to_acquire_leader()
def __write_leader_optime_or_history_value(self, key, value):
value = value.encode('utf-8')
try:
self._client.set_async(key, value).get(timeout=1)
return True
except NoNodeError:
try:
self._client.create_async(key, value, makepath=True).get(timeout=1)
return True
except Exception:
logger.exception('Failed to create %s', key)
except Exception:
logger.exception('Failed to update %s', key)
return False
def _write_leader_optime(self, last_operation): def _write_leader_optime(self, last_operation):
return self.__write_leader_optime_or_history_value(self.leader_optime_path, last_operation) return self._set_or_create(self.leader_optime_path, last_operation)
def _update_leader(self): def _update_leader(self):
return True return True
def delete_leader(self): def delete_leader(self):
self._client.restart() self._client.restart()
self._my_member_data = None
return True return True
def _cancel_initialization(self): def _cancel_initialization(self):
@@ -330,10 +318,10 @@ class ZooKeeper(AbstractDCS):
return True return True
def set_history_value(self, value): def set_history_value(self, value):
return self.__write_leader_optime_or_history_value(self.history_path, value) return self._set_or_create(self.history_path, value)
def set_sync_state_value(self, value, index=None): def set_sync_state_value(self, value, index=None):
return self.__set_failover_or_sync_state_value(self.sync_path, value, index) return self._set_or_create(self.sync_path, value, index, retry=True, do_not_create_empty=True)
def delete_sync_state(self, index=None): def delete_sync_state(self, index=None):
return self.set_sync_state_value("{}", index) return self.set_sync_state_value("{}", index)
+100 -13
View File
@@ -6,6 +6,7 @@ import psycopg2
import requests import requests
import sys import sys
import time import time
import uuid
from collections import namedtuple from collections import namedtuple
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
@@ -13,6 +14,7 @@ from patroni.async_executor import AsyncExecutor, CriticalTask
from patroni.exceptions import DCSError, PostgresConnectionException, PatroniException from patroni.exceptions import DCSError, PostgresConnectionException, PatroniException
from patroni.postgresql import ACTION_ON_START from patroni.postgresql import ACTION_ON_START
from patroni.utils import polling_loop, tzutc from patroni.utils import polling_loop, tzutc
from patroni.dcs import RemoteMember
from threading import RLock from threading import RLock
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -105,6 +107,9 @@ class Ha(object):
self.old_cluster = cluster self.old_cluster = cluster
self.cluster = cluster self.cluster = cluster
if self.cluster.is_unlocked() or self.cluster.leader.name != self.state_handler.name:
self.set_is_leader(False)
self._leader_timeline = None if cluster.is_unlocked() else cluster.leader.timeline self._leader_timeline = None if cluster.is_unlocked() else cluster.leader.timeline
def acquire_lock(self): def acquire_lock(self):
@@ -190,14 +195,24 @@ class Ha(object):
self._async_executor.schedule('bootstrap {0}'.format(msg)) self._async_executor.schedule('bootstrap {0}'.format(msg))
self._async_executor.run_async(self.clone, args=(clone_member, msg)) self._async_executor.run_async(self.clone, args=(clone_member, msg))
return 'trying to bootstrap {0}'.format(msg) return 'trying to bootstrap {0}'.format(msg)
# no initialize key and node is allowed to be master and has 'bootstrap' section in a configuration file # no initialize key and node is allowed to be master and has 'bootstrap' section in a configuration file
elif self.cluster.initialize is None and not self.patroni.nofailover and 'bootstrap' in self.patroni.config: elif self.cluster.initialize is None and not self.patroni.nofailover and 'bootstrap' in self.patroni.config:
if self.dcs.initialize(create_new=True): # race for initialization if self.dcs.initialize(create_new=True): # race for initialization
self.state_handler.bootstrapping = True self.state_handler.bootstrapping = True
self._post_bootstrap_task = CriticalTask() self._post_bootstrap_task = CriticalTask()
self._async_executor.schedule('bootstrap')
self._async_executor.run_async(self.state_handler.bootstrap, args=(self.patroni.config['bootstrap'],)) if self.patroni.config.is_standby_cluster:
return 'trying to bootstrap a new cluster' self._async_executor.schedule('bootstrap_standby_leader')
self._async_executor.run_async(self.bootstrap_standby_leader)
return 'trying to bootstrap a new standby leader'
else:
self._async_executor.schedule('bootstrap')
self._async_executor.run_async(
self.state_handler.bootstrap,
args=(self.patroni.config['bootstrap'],)
)
return 'trying to bootstrap a new cluster'
else: else:
return 'failed to acquire initialize lock' return 'failed to acquire initialize lock'
else: else:
@@ -208,6 +223,21 @@ class Ha(object):
return 'trying to ' + msg return 'trying to ' + msg
return 'waiting for leader to bootstrap' return 'waiting for leader to bootstrap'
def bootstrap_standby_leader(self):
""" If we found 'standby' key in the configuration, we need to bootstrap
not a real master, but a 'standby leader', that will take base backup
from a remote master and start follow it.
"""
patroni_config = self.patroni.config.dynamic_configuration
clone_source = self.get_remote_master(patroni_config)
msg = 'clone from remote master {0}'.format(clone_source.conn_url)
result = self.clone(clone_source, msg)
self._post_bootstrap_task.complete(result)
if result:
self.state_handler.set_role('standby_leader')
return result
def _handle_rewind(self): def _handle_rewind(self):
if self.state_handler.rewind_needed_and_possible(self.cluster.leader): if self.state_handler.rewind_needed_and_possible(self.cluster.leader):
self._async_executor.schedule('running pg_rewind from ' + self.cluster.leader.name) self._async_executor.schedule('running pg_rewind from ' + self.cluster.leader.name)
@@ -263,12 +293,18 @@ class Ha(object):
def _get_node_to_follow(self, cluster): def _get_node_to_follow(self, cluster):
# determine the node to follow. If replicatefrom tag is set, # determine the node to follow. If replicatefrom tag is set,
# try to follow the node mentioned there, otherwise, follow the leader. # try to follow the node mentioned there, otherwise, follow the leader.
if not self.patroni.replicatefrom or self.patroni.replicatefrom == self.state_handler.name: is_leader = self.cluster.leader and self.state_handler.name == self.cluster.leader.name
node_to_follow = cluster.leader
else:
node_to_follow = cluster.get_member(self.patroni.replicatefrom)
return node_to_follow if node_to_follow and node_to_follow.name != self.state_handler.name else None if self.cluster.is_standby_cluster() and is_leader:
node_to_follow = self.get_remote_master(cluster.config.data)
elif self.patroni.replicatefrom and self.patroni.replicatefrom != self.state_handler.name:
node_to_follow = cluster.get_member(self.patroni.replicatefrom)
else:
node_to_follow = cluster.leader
return (node_to_follow if
node_to_follow and
node_to_follow.name != self.state_handler.name else None)
def follow(self, demote_reason, follow_reason, refresh=True): def follow(self, demote_reason, follow_reason, refresh=True):
if refresh: if refresh:
@@ -408,6 +444,12 @@ class Ha(object):
line.append(cluster_history[line[0]][3]) line.append(cluster_history[line[0]][3])
self.dcs.set_history_value(json.dumps(history, separators=(',', ':'))) self.dcs.set_history_value(json.dumps(history, separators=(',', ':')))
def enforce_follow_remote_master(self, message):
self.state_handler.set_role('standby_leader')
demote_reason = 'cannot be a real master in standby cluster'
return self.follow(demote_reason, message)
def enforce_master_role(self, message, promote_message): def enforce_master_role(self, message, promote_message):
if not self.is_paused() and not self.watchdog.is_running and not self.watchdog.activate(): if not self.is_paused() and not self.watchdog.is_running and not self.watchdog.activate():
if self.state_handler.is_leader(): if self.state_handler.is_leader():
@@ -452,7 +494,7 @@ class Ha(object):
logger.info('Got response from %s %s: %s', member.name, member.api_url, response.content) logger.info('Got response from %s %s: %s', member.name, member.api_url, response.content)
return _MemberStatus.from_api_response(member, response.json()) return _MemberStatus.from_api_response(member, response.json())
except Exception as e: except Exception as e:
logger.warning("request failed: GET %s (%s)", member.api_url, e) logger.warning("Request failed to %s: GET %s (%s)", member.name, member.api_url, e)
return _MemberStatus.unknown(member) return _MemberStatus.unknown(member)
def fetch_nodes_statuses(self, members): def fetch_nodes_statuses(self, members):
@@ -620,6 +662,7 @@ class Ha(object):
self.state_handler.stop(mode_control['stop'], checkpoint=mode_control['checkpoint'], self.state_handler.stop(mode_control['stop'], checkpoint=mode_control['checkpoint'],
on_safepoint=self.watchdog.disable if self.watchdog.is_running else None) on_safepoint=self.watchdog.disable if self.watchdog.is_running else None)
self.state_handler.set_role('demoted') self.state_handler.set_role('demoted')
self.set_is_leader(False)
if mode_control['release']: if mode_control['release']:
self.release_leader_key_voluntarily() self.release_leader_key_voluntarily()
@@ -736,8 +779,18 @@ class Ha(object):
logger.info('Cleaning up failover key after acquiring leader lock...') logger.info('Cleaning up failover key after acquiring leader lock...')
self.dcs.manual_failover('', '') self.dcs.manual_failover('', '')
self.load_cluster_from_dcs() self.load_cluster_from_dcs()
return self.enforce_master_role('acquired session lock as a leader',
'promoted self to leader by acquiring session lock') if self.cluster.is_standby_cluster():
# standby leader disappeared, and this is a healthiest
# replica, so it should become a new standby leader.
# This imply that we need to start following a remote master
msg = 'promoted self to a standby leader because i had the session lock'
return self.enforce_follow_remote_master(msg)
else:
return self.enforce_master_role(
'acquired session lock as a leader',
'promoted self to leader by acquiring session lock'
)
else: else:
return self.follow('demoted self after trying and failing to obtain lock', return self.follow('demoted self after trying and failing to obtain lock',
'following new leader after trying and failing to obtain lock') 'following new leader after trying and failing to obtain lock')
@@ -769,8 +822,17 @@ class Ha(object):
if msg is not None: if msg is not None:
return msg return msg
return self.enforce_master_role('no action. i am the leader with the lock', if self.cluster.is_standby_cluster():
'promoted self to leader because i had the session lock') # in case of standby cluster we don't really need to
# enforce anything, since the leader is not a master.
# So just remind the role.
msg = 'no action. i am the standby leader with the lock'
return self.enforce_follow_remote_master(msg)
else:
return self.enforce_master_role(
'no action. i am the leader with the lock',
'promoted self to leader because i had the session lock'
)
else: else:
# Either there is no connection to DCS or someone else acquired the lock # Either there is no connection to DCS or someone else acquired the lock
logger.error('failed to update leader lock') logger.error('failed to update leader lock')
@@ -997,6 +1059,7 @@ class Ha(object):
self.set_is_leader(True) self.set_is_leader(True)
self.state_handler.call_nowait(ACTION_ON_START) self.state_handler.call_nowait(ACTION_ON_START)
self.load_cluster_from_dcs() self.load_cluster_from_dcs()
return 'initialized a new cluster' return 'initialized a new cluster'
def handle_starting_instance(self): def handle_starting_instance(self):
@@ -1211,3 +1274,27 @@ class Ha(object):
no "active" leader watch request in progress. no "active" leader watch request in progress.
This usually happens on the master or if the node is running async action""" This usually happens on the master or if the node is running async action"""
self.dcs.event.set() self.dcs.event.set()
def get_remote_master(self, config):
""" In case of standby cluster this will tel us from which remote
master to stream. Config can be both patroni config or
cluster.config.data
"""
config = config or (self.config is not None and self.config.data)
if config and config.get('standby_cluster'):
cluster_params = config.get('standby_cluster')
unique_name = 'remote_master:{}'.format(uuid.uuid1())
data = {
'conn_kwargs': {
"host": cluster_params.get('host'),
"port": cluster_params.get('port'),
},
'no_replication_slot': 'primary_slot_name' not in cluster_params,
}
data.update({
k: v for k, v in cluster_params.items()
if k in RemoteMember.allowed_keys()
})
return RemoteMember(unique_name, data)
+38 -11
View File
@@ -15,11 +15,13 @@ from patroni.callback_executor import CallbackExecutor
from patroni.exceptions import PostgresConnectionException, PostgresException from patroni.exceptions import PostgresConnectionException, PostgresException
from patroni.utils import compare_values, parse_bool, parse_int, Retry, RetryFailedError, polling_loop, split_host_port from patroni.utils import compare_values, parse_bool, parse_int, Retry, RetryFailedError, polling_loop, split_host_port
from patroni.postmaster import PostmasterProcess from patroni.postmaster import PostmasterProcess
from patroni.dcs import RemoteMember
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
from six import string_types from six import string_types
from six.moves.urllib.parse import quote_plus from six.moves.urllib.parse import quote_plus
from threading import current_thread, Lock from threading import current_thread, Lock
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
ACTION_ON_START = "on_start" ACTION_ON_START = "on_start"
@@ -665,9 +667,17 @@ class Postgresql(object):
self.set_state('creating replica') self.set_state('creating replica')
self._sysid = None self._sysid = None
# get list of replica methods from config. is_remote_master = isinstance(clone_member, RemoteMember)
# If there is no configuration key, or no value is specified, use basebackup create_replica_methods = is_remote_master and clone_member.create_replica_methods
replica_methods = self._create_replica_methods or ['basebackup']
# get list of replica methods either from clone member or from
# the config. If there is no configuration key, or no value is
# specified, use basebackup
replica_methods = (
create_replica_methods
or self._create_replica_methods
or ['basebackup']
)
if clone_member and clone_member.conn_url: if clone_member and clone_member.conn_url:
r = clone_member.conn_kwargs(self._replication) r = clone_member.conn_kwargs(self._replication)
@@ -945,7 +955,7 @@ class Postgresql(object):
return 'is_in_recovery=true' return 'is_in_recovery=true'
return cur.execute('CHECKPOINT') return cur.execute('CHECKPOINT')
except psycopg2.Error: except psycopg2.Error:
logging.exception('Exception during CHECKPOINT') logger.exception('Exception during CHECKPOINT')
return 'not accessible or not healty' return 'not accessible or not healty'
def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None): def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None):
@@ -1216,7 +1226,8 @@ class Postgresql(object):
if data: if data:
data = data.decode('utf-8').splitlines() data = data.decode('utf-8').splitlines()
# pg_controldata output depends on major verion. Some of parameters are prefixed by 'Current ' # pg_controldata output depends on major verion. Some of parameters are prefixed by 'Current '
result = {l.split(':')[0].replace('Current ', '', 1): l.split(':', 1)[1].strip() for l in data if l} result = {l.split(':')[0].replace('Current ', '', 1): l.split(':', 1)[1].strip() for l in data
if l and ':' in l}
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
logger.exception("Error when calling pg_controldata") logger.exception("Error when calling pg_controldata")
return result return result
@@ -1412,6 +1423,12 @@ class Postgresql(object):
return self._rewind_state == REWIND_STATUS.FAILED return self._rewind_state == REWIND_STATUS.FAILED
def follow(self, member, timeout=None): def follow(self, member, timeout=None):
is_remote_master = isinstance(member, RemoteMember)
no_replication_slot = is_remote_master and member.no_replication_slot
restore_command = is_remote_master and member.restore_command
min_apply_delay = is_remote_master and member.recovery_min_apply_delay
archive_cleanup = is_remote_master and member.archive_cleanup_command
primary_conninfo = self.primary_conninfo(member) primary_conninfo = self.primary_conninfo(member)
change_role = self.role in ('master', 'demoted') change_role = self.role in ('master', 'demoted')
@@ -1419,8 +1436,16 @@ class Postgresql(object):
recovery_params.update({'standby_mode': 'on', 'recovery_target_timeline': 'latest'}) recovery_params.update({'standby_mode': 'on', 'recovery_target_timeline': 'latest'})
if primary_conninfo: if primary_conninfo:
recovery_params['primary_conninfo'] = primary_conninfo recovery_params['primary_conninfo'] = primary_conninfo
if self.use_slots: if self.use_slots and not no_replication_slot:
recovery_params['primary_slot_name'] = slot_name_from_member_name(self.name) required_name = is_remote_master and member.data.get('primary_slot_name')
name = required_name or slot_name_from_member_name(self.name)
recovery_params['primary_slot_name'] = name
if restore_command:
recovery_params['restore_command'] = restore_command
if min_apply_delay:
recovery_params['recovery_min_apply_delay'] = min_apply_delay
if archive_cleanup:
recovery_params['archive_cleanup_command'] = archive_cleanup
self.write_recovery_conf(recovery_params) self.write_recovery_conf(recovery_params)
@@ -1532,7 +1557,7 @@ $$""".format(name, ' '.join(options)), name, password, password)
# the current master, because that member would replicate from elsewhere. We still create the slot if # the current master, because that member would replicate from elsewhere. We still create the slot if
# the replicatefrom destination member is currently not a member of the cluster (fallback to the # the replicatefrom destination member is currently not a member of the cluster (fallback to the
# master), or if replicatefrom destination member happens to be the current master # master), or if replicatefrom destination member happens to be the current master
if self.role == 'master': if self.role in ('master', 'standby_leader'):
slot_members = [m.name for m in cluster.members if m.name != self.name and slot_members = [m.name for m in cluster.members if m.name != self.name and
(m.replicatefrom is None or m.replicatefrom == self.name or (m.replicatefrom is None or m.replicatefrom == self.name or
not cluster.has_member(m.replicatefrom))] not cluster.has_member(m.replicatefrom))]
@@ -1560,11 +1585,13 @@ $$""".format(name, ' '.join(options)), name, password, password)
if cursor.rowcount != 1: # Either slot doesn't exists or it is still active if cursor.rowcount != 1: # Either slot doesn't exists or it is still active
self._schedule_load_slots = True # schedule load_replication_slots on the next iteration self._schedule_load_slots = True # schedule load_replication_slots on the next iteration
immediately_reserve = ', true' if self._major_version >= 90600 else ''
# create new slots # create new slots
for slot in slots - set(self._replication_slots): for slot in slots - set(self._replication_slots):
self._query("""SELECT pg_create_physical_replication_slot(%s) self._query("""SELECT pg_create_physical_replication_slot(%s{0})
WHERE NOT EXISTS (SELECT 1 FROM pg_replication_slots WHERE NOT EXISTS (SELECT 1 FROM pg_replication_slots
WHERE slot_name = %s)""", slot, slot) WHERE slot_name = %s)""".format(immediately_reserve), slot, slot)
self._replication_slots = slots self._replication_slots = slots
except Exception: except Exception:
@@ -1733,7 +1760,7 @@ $$""".format(name, ' '.join(options)), name, password, password)
if sync_state == 'potential' and app_name == current: if sync_state == 'potential' and app_name == current:
# Prefer current even if not the best one any more to avoid indecisivness and spurious swaps. # Prefer current even if not the best one any more to avoid indecisivness and spurious swaps.
return current, False return current, False
if sync_state == 'async': if sync_state in ('async', 'potential'):
candidates.append(app_name) candidates.append(app_name)
if candidates: if candidates:
+1 -1
View File
@@ -1 +1 @@
__version__ = '1.4.5' __version__ = '1.4.6'
+9
View File
@@ -11,6 +11,11 @@ restapi:
# username: username # username: username
# password: password # password: password
# ctl:
# insecure: false # Allow connections to SSL sites without certs
# certfile: /etc/ssl/certs/ssl-cert-snakeoil.pem
# cacert: /etc/ssl/certs/ssl-cacert-snakeoil.pem
etcd: etcd:
host: 127.0.0.1:2379 host: 127.0.0.1:2379
@@ -24,6 +29,10 @@ bootstrap:
maximum_lag_on_failover: 1048576 maximum_lag_on_failover: 1048576
# master_start_timeout: 300 # master_start_timeout: 300
# synchronous_mode: false # synchronous_mode: false
#standby_cluster:
#host: 127.0.0.1
#port: 1111
#primary_slot_name: patroni
postgresql: postgresql:
use_pg_rewind: true use_pg_rewind: true
# use_slots: true # use_slots: true
+5
View File
@@ -11,6 +11,11 @@ restapi:
# username: username # username: username
# password: password # password: password
# ctl:
# insecure: false # Allow connections to SSL sites without certs
# certfile: /etc/ssl/certs/ssl-cert-snakeoil.pem
# cacert: /etc/ssl/certs/ssl-cacert-snakeoil.pem
etcd: etcd:
host: 127.0.0.1:2379 host: 127.0.0.1:2379
+5
View File
@@ -11,6 +11,11 @@ restapi:
username: username username: username
password: password password: password
# ctl:
# insecure: false # Allow connections to SSL sites without certs
# certfile: /etc/ssl/certs/ssl-cert-snakeoil.pem
# cacert: /etc/ssl/certs/ssl-cacert-snakeoil.pem
etcd: etcd:
host: 127.0.0.1:2379 host: 127.0.0.1:2379
+8 -4
View File
@@ -32,9 +32,10 @@ VERSION = read_version(MAIN_PACKAGE)
DESCRIPTION = 'PostgreSQL High-Available orchestrator and CLI' DESCRIPTION = 'PostgreSQL High-Available orchestrator and CLI'
LICENSE = 'The MIT License' LICENSE = 'The MIT License'
URL = 'https://github.com/zalando/patroni' URL = 'https://github.com/zalando/patroni'
AUTHOR = 'Alexander Kukushkin, Oleksii Kliukin, Feike Steenbergen' AUTHOR = 'Alexander Kukushkin, Dmitrii Dolgov, Oleksii Kliukin'
AUTHOR_EMAIL = '[email protected], [email protected], [email protected]' AUTHOR_EMAIL = '[email protected], [email protected], [email protected]'
KEYWORDS = 'etcd governor patroni postgresql postgres ha haproxy confd zookeeper exhibitor consul streaming replication' KEYWORDS = 'etcd governor patroni postgresql postgres ha haproxy confd' +\
' zookeeper exhibitor consul streaming replication kubernetes k8s'
COVERAGE_XML = True COVERAGE_XML = True
COVERAGE_HTML = False COVERAGE_HTML = False
@@ -43,14 +44,17 @@ JUNIT_XML = True
# Add here all kinds of additional classifiers as defined under # Add here all kinds of additional classifiers as defined under
# https://pypi.python.org/pypi?%3Aaction=list_classifiers # https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [ CLASSIFIERS = [
'Development Status :: 4 - Beta', 'Development Status :: 5 - Production/Stable',
'Environment :: Console', 'Environment :: Console',
'Intended Audience :: Developers', 'Intended Audience :: Developers',
'Intended Audience :: System Administrators', 'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License', 'License :: OSI Approved :: MIT License',
'Operating System :: MacOS',
'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: BSD :: FreeBSD',
'Programming Language :: Python', 'Programming Language :: Python',
'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.6',
+1
View File
@@ -155,6 +155,7 @@ class TestRestApiHandler(unittest.TestCase):
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})): with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})):
MockRestApiServer(RestApiHandler, 'GET /synchronous') MockRestApiServer(RestApiHandler, 'GET /synchronous')
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})): with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})):
MockPatroni.dcs.cluster.sync.sync_standby = ''
MockRestApiServer(RestApiHandler, 'GET /asynchronous') MockRestApiServer(RestApiHandler, 'GET /asynchronous')
MockPatroni.ha.is_leader = Mock(return_value=True) MockPatroni.ha.is_leader = Mock(return_value=True)
MockRestApiServer(RestApiHandler, 'GET /replica') MockRestApiServer(RestApiHandler, 'GET /replica')
+2 -1
View File
@@ -23,7 +23,7 @@ class TestConfig(unittest.TestCase):
def test_set_dynamic_configuration(self): def test_set_dynamic_configuration(self):
with patch.object(Config, '_build_effective_configuration', Mock(side_effect=Exception)): with patch.object(Config, '_build_effective_configuration', Mock(side_effect=Exception)):
self.assertIsNone(self.config.set_dynamic_configuration({'foo': 'bar'})) self.assertIsNone(self.config.set_dynamic_configuration({'foo': 'bar'}))
self.assertTrue(self.config.set_dynamic_configuration({'synchronous_mode': True})) self.assertTrue(self.config.set_dynamic_configuration({'synchronous_mode': True, 'standby_cluster': {}}))
def test_reload_local_configuration(self): def test_reload_local_configuration(self):
os.environ.update({ os.environ.update({
@@ -70,6 +70,7 @@ class TestConfig(unittest.TestCase):
self.assertRaises(Exception, config.reload_local_configuration, True) self.assertRaises(Exception, config.reload_local_configuration, True)
self.assertTrue(config.reload_local_configuration(True)) self.assertTrue(config.reload_local_configuration(True))
self.assertTrue(config.reload_local_configuration()) self.assertTrue(config.reload_local_configuration())
self.assertIsNone(config.reload_local_configuration())
@patch('tempfile.mkstemp', Mock(return_value=[3000, 'blabla'])) @patch('tempfile.mkstemp', Mock(return_value=[3000, 'blabla']))
@patch('os.path.exists', Mock(return_value=True)) @patch('os.path.exists', Mock(return_value=True))
+26 -6
View File
@@ -62,7 +62,7 @@ class TestHTTPClient(unittest.TestCase):
def test_put(self): def test_put(self):
self.client.put(Mock(), '/v1/session/create') self.client.put(Mock(), '/v1/session/create')
self.client.put(Mock(), '/v1/session/create', data='{"foo": "bar"}') self.client.put(Mock(), '/v1/session/create', params=[], data='{"foo": "bar"}')
@patch.object(consul.Consul.KV, 'get', kv_get) @patch.object(consul.Consul.KV, 'get', kv_get)
@@ -74,10 +74,12 @@ class TestConsul(unittest.TestCase):
@patch.object(consul.Consul.KV, 'delete', Mock()) @patch.object(consul.Consul.KV, 'delete', Mock())
def setUp(self): def setUp(self):
Consul({'ttl': 30, 'scope': 't', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10, Consul({'ttl': 30, 'scope': 't', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10,
'verify': 'on', 'key': 'foo', 'cert': 'bar', 'cacert': 'buz', 'token': 'asd', 'dc': 'dc1'}) 'verify': 'on', 'key': 'foo', 'cert': 'bar', 'cacert': 'buz', 'token': 'asd', 'dc': 'dc1',
Consul({'ttl': 30, 'scope': 't', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10, 'register_service': True})
'verify': 'on', 'cert': 'bar', 'cacert': 'buz'}) Consul({'ttl': 30, 'scope': 't_', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10,
self.c = Consul({'ttl': 30, 'scope': 'test', 'name': 'postgresql1', 'host': 'localhost:1', 'retry_timeout': 10}) 'verify': 'on', 'cert': 'bar', 'cacert': 'buz', 'register_service': True})
self.c = Consul({'ttl': 30, 'scope': 'test', 'name': 'postgresql1', 'host': 'localhost:1', 'retry_timeout': 10,
'register_service': True})
self.c._base_path = '/service/good' self.c._base_path = '/service/good'
self.c._load_cluster() self.c._load_cluster()
@@ -111,12 +113,14 @@ class TestConsul(unittest.TestCase):
@patch.object(consul.Consul.KV, 'delete', Mock(side_effect=[ConsulException, True, True])) @patch.object(consul.Consul.KV, 'delete', Mock(side_effect=[ConsulException, True, True]))
@patch.object(consul.Consul.KV, 'put', Mock(side_effect=[True, ConsulException])) @patch.object(consul.Consul.KV, 'put', Mock(side_effect=[True, ConsulException]))
def test_touch_member(self): def test_touch_member(self):
self.c._register_service = True
self.c.refresh_session = Mock(return_value=True) self.c.refresh_session = Mock(return_value=True)
self.c.touch_member({'balbla': 'blabla'}) self.c.touch_member({'balbla': 'blabla'})
self.c.touch_member({'balbla': 'blabla'}) self.c.touch_member({'balbla': 'blabla'})
self.c.touch_member({'balbla': 'blabla'}) self.c.touch_member({'balbla': 'blabla'})
self.c.refresh_session = Mock(return_value=False) self.c.refresh_session = Mock(return_value=False)
self.c.touch_member({'balbla': 'blabla'}) self.c.touch_member({'conn_url': 'postgres://replicator:[email protected]:5433/postgres',
'api_url': 'http://127.0.0.1:8009/patroni'})
@patch.object(consul.Consul.KV, 'put', Mock(return_value=False)) @patch.object(consul.Consul.KV, 'put', Mock(return_value=False))
def test_take_leader(self): def test_take_leader(self):
@@ -176,3 +180,19 @@ class TestConsul(unittest.TestCase):
@patch.object(consul.Consul.KV, 'put', Mock(return_value=True)) @patch.object(consul.Consul.KV, 'put', Mock(return_value=True))
def test_set_history_value(self): def test_set_history_value(self):
self.assertTrue(self.c.set_history_value('{}')) self.assertTrue(self.c.set_history_value('{}'))
@patch.object(consul.Consul.Agent.Service, 'register', Mock(side_effect=(False, True)))
@patch.object(consul.Consul.Agent.Service, 'deregister', Mock(return_value=True))
def test_update_service(self):
d = {'role': 'replica', 'api_url': 'http://a/t', 'conn_url': 'pg://c:1', 'state': 'running'}
self.assertIsNone(self.c.update_service({}, {}))
self.assertFalse(self.c.update_service({}, d))
self.assertTrue(self.c.update_service(d, d))
self.assertIsNone(self.c.update_service(d, d))
d['state'] = 'stopped'
self.assertTrue(self.c.update_service(d, d, force=True))
d['state'] = 'unknown'
self.assertIsNone(self.c.update_service({}, d))
d['state'] = 'running'
d['role'] = 'bla'
self.assertIsNone(self.c.update_service({}, d))
+23 -1
View File
@@ -225,6 +225,22 @@ class TestCtl(unittest.TestCase):
result = self.runner.invoke(ctl, ['dsn', 'alpha', '--member', 'dummy']) result = self.runner.invoke(ctl, ['dsn', 'alpha', '--member', 'dummy'])
assert result.exit_code == 1 assert result.exit_code == 1
@patch('requests.post')
@patch('patroni.ctl.get_dcs')
def test_reload(self, mock_get_dcs, mock_post):
mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader
result = self.runner.invoke(ctl, ['reload', 'alpha'], input='y')
assert 'Failed: reload for member' in result.output
mock_post.return_value.status_code = 200
result = self.runner.invoke(ctl, ['reload', 'alpha'], input='y')
assert 'No changes to apply on member' in result.output
mock_post.return_value.status_code = 202
result = self.runner.invoke(ctl, ['reload', 'alpha'], input='y')
assert 'Reload request received for member' in result.output
@patch('requests.post', requests_get) @patch('requests.post', requests_get)
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
def test_restart_reinit(self, mock_get_dcs): def test_restart_reinit(self, mock_get_dcs):
@@ -328,8 +344,14 @@ class TestCtl(unittest.TestCase):
assert result.exit_code == 0 assert result.exit_code == 0
@patch('requests.post', Mock(side_effect=requests.exceptions.ConnectionError('foo'))) @patch('requests.post', Mock(side_effect=requests.exceptions.ConnectionError('foo')))
def test_request_patroni(self): @patch('click.get_current_context')
def test_request_patroni(self, mock_context):
member = get_cluster_initialized_with_leader().leader.member member = get_cluster_initialized_with_leader().leader.member
mock_context.return_value.obj = {'ctl': {'cacert': 'cert.pem'}}
self.assertRaises(requests.exceptions.ConnectionError, request_patroni, member, 'post', 'dummy', {})
mock_context.return_value.obj = {'ctl': {'insecure': True}}
self.assertRaises(requests.exceptions.ConnectionError, request_patroni, member, 'post', 'dummy', {}) self.assertRaises(requests.exceptions.ConnectionError, request_patroni, member, 'post', 'dummy', {})
def test_ctl(self): def test_ctl(self):
+139 -8
View File
@@ -2,8 +2,10 @@ import datetime
import etcd import etcd
import os import os
import unittest import unittest
import sys
from mock import Mock, MagicMock, PropertyMock, patch from mock import Mock, MagicMock, PropertyMock, patch
from patroni.async_executor import CriticalTask
from patroni.config import Config from patroni.config import Config
from patroni.dcs import Cluster, ClusterConfig, Failover, Leader, Member, get_dcs, SyncState, TimelineHistory from patroni.dcs import Cluster, ClusterConfig, Failover, Leader, Member, get_dcs, SyncState, TimelineHistory
from patroni.dcs.etcd import Client from patroni.dcs.etcd import Client
@@ -26,16 +28,17 @@ def false(*args, **kwargs):
return False return False
def get_cluster(initialize, leader, members, failover, sync): def get_cluster(initialize, leader, members, failover, sync, cluster_config=None):
history = TimelineHistory(1, [(1, 67197376, 'no recovery target specified', datetime.datetime.now().isoformat())]) history = TimelineHistory(1, [(1, 67197376, 'no recovery target specified', datetime.datetime.now().isoformat())])
return Cluster(initialize, ClusterConfig(1, {1: 2}, 1), leader, 10, members, failover, sync, history) cluster_config = cluster_config or ClusterConfig(1, {1: 2}, 1)
return Cluster(initialize, cluster_config, leader, 10, members, failover, sync, history)
def get_cluster_not_initialized_without_leader(): def get_cluster_not_initialized_without_leader(cluster_config=None):
return get_cluster(None, None, [], None, SyncState(None, None, None)) return get_cluster(None, None, [], None, SyncState(None, None, None), cluster_config)
def get_cluster_initialized_without_leader(leader=False, failover=None, sync=None): def get_cluster_initialized_without_leader(leader=False, failover=None, sync=None, cluster_config=None):
m1 = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres', m1 = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres',
'api_url': 'http://127.0.0.1:8008/patroni', 'xlog_location': 4}) 'api_url': 'http://127.0.0.1:8008/patroni', 'xlog_location': 4})
leader = Leader(0, 0, m1) if leader else None leader = Leader(0, 0, m1) if leader else None
@@ -47,16 +50,38 @@ def get_cluster_initialized_without_leader(leader=False, failover=None, sync=Non
'scheduled_restart': {'schedule': "2100-01-01 10:53:07.560445+00:00", 'scheduled_restart': {'schedule': "2100-01-01 10:53:07.560445+00:00",
'postgres_version': '99.0.0'}}) 'postgres_version': '99.0.0'}})
syncstate = SyncState(0 if sync else None, sync and sync[0], sync and sync[1]) syncstate = SyncState(0 if sync else None, sync and sync[0], sync and sync[1])
return get_cluster(SYSID, leader, [m1, m2], failover, syncstate) return get_cluster(SYSID, leader, [m1, m2], failover, syncstate, cluster_config)
def get_cluster_initialized_with_leader(failover=None, sync=None): def get_cluster_initialized_with_leader(failover=None, sync=None):
return get_cluster_initialized_without_leader(leader=True, failover=failover, sync=sync) return get_cluster_initialized_without_leader(leader=True, failover=failover, sync=sync)
def get_cluster_initialized_with_only_leader(failover=None): def get_cluster_initialized_with_only_leader(failover=None, cluster_config=None):
leader = get_cluster_initialized_without_leader(leader=True, failover=failover).leader leader = get_cluster_initialized_without_leader(leader=True, failover=failover).leader
return get_cluster(True, leader, [leader], failover, None) return get_cluster(True, leader, [leader], failover, None, cluster_config)
def get_cluster_not_initialized_standby(failover=None, sync=None):
return get_cluster_not_initialized_without_leader(
cluster_config=ClusterConfig(1, {
"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}, 1)
)
def get_standby_cluster_initialized_with_only_leader(failover=None, sync=None):
return get_cluster_initialized_with_only_leader(
cluster_config=ClusterConfig(1, {
"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}, 1)
)
def get_node_status(reachable=True, in_recovery=True, wal_position=10, nofailover=False, watchdog_failed=False): def get_node_status(reachable=True, in_recovery=True, wal_position=10, nofailover=False, watchdog_failed=False):
@@ -97,6 +122,10 @@ zookeeper:
hosts: [localhost] hosts: [localhost]
port: 8181 port: 8181
""" """
# We rely on sys.argv in Config, so it's necessary to reset
# all the extra values that are coming from py.test
sys.argv = sys.argv[:1]
self.config = Config() self.config = Config()
self.postgresql = p self.postgresql = p
self.dcs = d self.dcs = d
@@ -175,10 +204,57 @@ class TestHa(unittest.TestCase):
self.p.replica_cached_timeline = Mock(side_effect=Exception) self.p.replica_cached_timeline = Mock(side_effect=Exception)
self.ha.touch_member() self.ha.touch_member()
def test_is_leader(self):
self.assertFalse(self.ha.is_leader())
def test_start_as_replica(self): def test_start_as_replica(self):
self.p.is_healthy = false self.p.is_healthy = false
self.assertEquals(self.ha.run_cycle(), 'starting as a secondary') self.assertEquals(self.ha.run_cycle(), 'starting as a secondary')
@patch('patroni.dcs.etcd.Etcd.initialize', return_value=True)
def test_start_as_standby_leader(self, initialize):
self.p.data_directory_empty = true
self.ha.cluster = get_cluster_not_initialized_standby()
self.ha.cluster.is_unlocked = true
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.assertEquals(
self.ha.run_cycle(),
'trying to bootstrap a new standby leader'
)
@patch.object(Cluster, 'get_clone_member',
Mock(return_value=Member(0, 'test', 1, {'api_url': 'http://127.0.0.1:8011/patroni'})))
@patch.object(Postgresql, 'create_replica', Mock(return_value=0))
def test_start_as_cascade_replica_in_standby_cluster(self):
self.p.data_directory_empty = true
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.cluster.is_unlocked = false
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.assertEquals(
self.ha.run_cycle(),
"trying to bootstrap from replica 'test'"
)
@patch.object(Postgresql, 'create_replica', Mock(return_value=0))
def test_bootstrap_standby_leader(self):
self.ha.cluster = get_cluster_not_initialized_standby()
self.ha.cluster.is_unlocked = true
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.ha._post_bootstrap_task = CriticalTask()
self.assertEquals(self.ha.bootstrap_standby_leader(), True)
def test_recover_replica_failed(self): def test_recover_replica_failed(self):
self.p.controldata = lambda: {'Database cluster state': 'in recovery', 'Database system identifier': SYSID} self.p.controldata = lambda: {'Database cluster state': 'in recovery', 'Database system identifier': SYSID}
self.p.is_running = false self.p.is_running = false
@@ -613,6 +689,61 @@ class TestHa(unittest.TestCase):
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', self.p.name, None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', self.p.name, None))
self.assertEquals(self.ha.run_cycle(), 'PAUSE: waiting to become master after promote...') self.assertEquals(self.ha.run_cycle(), 'PAUSE: waiting to become master after promote...')
def test_process_healthy_standby_cluster_as_standby_leader(self):
self.p.is_leader = false
self.p.name = 'leader'
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
msg = 'no action. i am the standby leader with the lock'
self.assertEquals(self.ha.run_cycle(), msg)
def test_process_healthy_standby_cluster_as_cascade_replica(self):
self.p.is_leader = false
self.p.name = 'replica'
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
msg = 'no action. i am a secondary and i am following a leader'
self.assertEquals(self.ha.run_cycle(), msg)
@patch('patroni.dcs.etcd.Etcd.initialize', return_value=True)
def test_process_unhealthy_standby_cluster_as_standby_leader(self, initialize):
self.p.is_leader = false
self.p.name = 'leader'
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.cluster.is_unlocked = true
self.ha.sysid_valid = true
self.p._sysid = True
msg = 'promoted self to a standby leader because i had the session lock'
self.assertEquals(self.ha.run_cycle(), msg)
@patch.object(Postgresql, 'rewind_needed_and_possible', Mock(return_value=True))
@patch('patroni.dcs.etcd.Etcd.initialize', return_value=True)
def test_process_unhealthy_standby_cluster_as_cascade_replica(self, initialize):
self.p.is_leader = false
self.p.name = 'replica'
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.is_unlocked = true
msg = 'running pg_rewind from leader'
self.assertEquals(self.ha.run_cycle(), msg)
def test_failed_to_update_lock_in_pause(self): def test_failed_to_update_lock_in_pause(self):
self.ha.update_lock = false self.ha.update_lock = false
self.ha.is_paused = true self.ha.is_paused = true
+2 -2
View File
@@ -8,7 +8,7 @@ import unittest
from mock import Mock, MagicMock, PropertyMock, patch, mock_open from mock import Mock, MagicMock, PropertyMock, patch, mock_open
from patroni.async_executor import CriticalTask from patroni.async_executor import CriticalTask
from patroni.dcs import Cluster, Leader, Member, SyncState from patroni.dcs import Cluster, Leader, Member, RemoteMember, SyncState
from patroni.exceptions import PostgresConnectionException, PostgresException from patroni.exceptions import PostgresConnectionException, PostgresException
from patroni.postgresql import Postgresql, STATE_REJECT, STATE_NO_RESPONSE from patroni.postgresql import Postgresql, STATE_REJECT, STATE_NO_RESPONSE
from patroni.postmaster import PostmasterProcess from patroni.postmaster import PostmasterProcess
@@ -401,7 +401,7 @@ class TestPostgresql(unittest.TestCase):
@patch.object(Postgresql, 'is_running', Mock(return_value=False)) @patch.object(Postgresql, 'is_running', Mock(return_value=False))
@patch.object(Postgresql, 'start', Mock()) @patch.object(Postgresql, 'start', Mock())
def test_follow(self): def test_follow(self):
self.p.follow(None) self.p.follow(RemoteMember('123', {'recovery_command': 'foo'}))
@patch('subprocess.check_output', Mock(return_value=0, side_effect=pg_controldata_string)) @patch('subprocess.check_output', Mock(return_value=0, side_effect=pg_controldata_string))
def test_can_rewind(self): def test_can_rewind(self):
+3 -2
View File
@@ -156,7 +156,7 @@ class TestZooKeeper(unittest.TestCase):
self.zk.set_failover_value('Exception') self.zk.set_failover_value('Exception')
def test_set_config_value(self): def test_set_config_value(self):
self.zk.set_config_value('') self.zk.set_config_value('', 1)
self.zk.set_config_value('ok') self.zk.set_config_value('ok')
self.zk.set_config_value('Exception') self.zk.set_config_value('Exception')
@@ -179,7 +179,8 @@ class TestZooKeeper(unittest.TestCase):
self.zk.touch_member({'retry': 'retry'}) self.zk.touch_member({'retry': 'retry'})
self.zk._fetch_cluster = True self.zk._fetch_cluster = True
self.zk.get_cluster() self.zk.get_cluster()
self.zk.touch_member({'retry': 'retry'}) self.zk.touch_member({'conn_url': 'postgres://repuser:rep-pass@localhost:5434/postgres',
'api_url': 'http://127.0.0.1:8009/patroni'})
def test_take_leader(self): def test_take_leader(self):
self.zk.take_leader() self.zk.take_leader()