mirror of
https://github.com/outbackdingo/patroni.git
synced 2026-08-26 15:40:21 +00:00
Compare commits
434
Commits
@@ -51,3 +51,9 @@ scm-source.json
|
||||
docs/build/
|
||||
docs/source/_static/
|
||||
docs/source/_templates/
|
||||
|
||||
# Pycharm IDE
|
||||
.idea/
|
||||
|
||||
#VSCode IDE
|
||||
.vscode/
|
||||
|
||||
+60
-17
@@ -1,17 +1,32 @@
|
||||
sudo: false
|
||||
sudo: true
|
||||
dist: trusty
|
||||
language: python
|
||||
python:
|
||||
- "3.4" # 2.7 and 3.5 are preinstalled by default
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- expect-dev # for unbuffer
|
||||
env:
|
||||
global:
|
||||
- ETCDVERSION=3.0.17 ZKVERSION=3.4.9 CONSULVERSION=0.7.4
|
||||
- PYVERSIONS="2.7 3.4 3.5"
|
||||
matrix:
|
||||
- TEST_SUITE="python setup.py"
|
||||
- DCS="etcd" TEST_SUITE="behave"
|
||||
- DCS="exhibitor" TEST_SUITE="behave"
|
||||
- DCS="consul" TEST_SUITE="behave"
|
||||
- ETCDVERSION=3.0.17 ZKVERSION=3.4.14 CONSULVERSION=0.7.4
|
||||
- PYVERSIONS="2.7 3.5 3.6"
|
||||
- EXCLUDE_BEHAVE="3.5"
|
||||
- BOTO_CONFIG=/doesnotexist
|
||||
matrix:
|
||||
include:
|
||||
- python: "3.5"
|
||||
env: TEST_SUITE="python setup.py"
|
||||
- python: "3.6"
|
||||
env: DCS="etcd" TEST_SUITE="behave"
|
||||
- python: "3.6"
|
||||
env: DCS="exhibitor" TEST_SUITE="behave"
|
||||
- python: "3.6"
|
||||
env: DCS="consul" TEST_SUITE="behave"
|
||||
- python: "3.6"
|
||||
env: DCS="kubernetes" TEST_SUITE="behave"
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- /^v\d+\.\d+(\.\d+)?$/
|
||||
cache:
|
||||
directories:
|
||||
- $HOME/mycache
|
||||
@@ -19,7 +34,7 @@ before_cache:
|
||||
- |
|
||||
rm -fr $HOME/mycache/python*
|
||||
for pv in $PYVERSIONS; do
|
||||
if [[ $TEST_SUITE != "behave" || $pv != "3.4" ]]; then
|
||||
if [[ $TEST_SUITE != "behave" || $pv != $EXCLUDE_BEHAVE ]]; then
|
||||
fpv=$(basename $(readlink $HOME/virtualenv/python${pv}))
|
||||
mv $HOME/virtualenv/${fpv} $HOME/mycache/${fpv}
|
||||
fi
|
||||
@@ -51,6 +66,26 @@ install:
|
||||
ln -s $EC etcd
|
||||
}
|
||||
|
||||
function get_kubernetes() {
|
||||
wget -O localkube "https://storage.googleapis.com/minikube/k8sReleases/v1.7.0/localkube-linux-amd64"
|
||||
chmod +x localkube
|
||||
sudo nohup ./localkube --logtostderr=true --enable-dns=false > localkube.log 2>&1 &
|
||||
|
||||
echo "Waiting for localkube to start..."
|
||||
if ! timeout 120 sh -c "while ! curl -ks http://127.0.0.1:8080/ >/dev/null; do sleep 1; done"; then
|
||||
sudo cat localkube.log
|
||||
echo "localkube did not start"
|
||||
exit 1
|
||||
fi
|
||||
echo "Check certificate permissions"
|
||||
sudo chmod 644 /var/lib/localkube/certs/*
|
||||
sudo ls -altr /var/lib/localkube/certs/
|
||||
|
||||
echo "Set up .kube/config"
|
||||
mkdir ~/.kube
|
||||
echo -e "apiVersion: v1\nclusters:\n- cluster:\n certificate-authority: /var/lib/localkube/certs/ca.crt\n server: https://127.0.0.1:8443\n name: local\ncontexts:\n- context:\n cluster: local\n user: myself\n name: local\ncurrent-context: local\nkind: Config\npreferences: {}\nusers:\n- name: myself\n user:\n client-certificate: /var/lib/localkube/certs/apiserver.crt\n client-key: /var/lib/localkube/certs/apiserver.key\n" > ~/.kube/config
|
||||
}
|
||||
|
||||
function get_exhibitor() {
|
||||
ZC=~/mycache/zookeeper-${ZKVERSION}
|
||||
if [[ ! -d $ZC ]]; then
|
||||
@@ -76,7 +111,7 @@ install:
|
||||
fi
|
||||
|
||||
for pv in $PYVERSIONS; do
|
||||
if [[ $TEST_SUITE != "behave" || $pv != "3.4" ]]; then
|
||||
if [[ $TEST_SUITE != "behave" || $pv != $EXCLUDE_BEHAVE ]]; then
|
||||
fpv=$(basename $(readlink $HOME/virtualenv/python$pv))
|
||||
if [[ -d ~/mycache/${fpv} ]]; then
|
||||
mv ~/virtualenv/${fpv} ~/virtualenv/${fpv}.bckp
|
||||
@@ -84,7 +119,7 @@ install:
|
||||
fi
|
||||
source ~/virtualenv/python${pv}/bin/activate
|
||||
# explicitly install all needed python modules to cache them
|
||||
for p in '-r requirements.txt' 'behave codacy-coverage coverage coveralls flake8 mock pytest-cov pytest setuptools'; do
|
||||
for p in '-r requirements.txt' 'psycopg2-binary behave codacy-coverage coverage coveralls flake8 mock pytest-cov pytest setuptools'; do
|
||||
pip install $p --upgrade
|
||||
done
|
||||
fi
|
||||
@@ -92,17 +127,21 @@ install:
|
||||
script:
|
||||
- |
|
||||
for pv in $PYVERSIONS; do
|
||||
if [[ $TEST_SUITE == "behave" && $pv == $EXCLUDE_BEHAVE ]]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
source ~/virtualenv/python${pv}/bin/activate
|
||||
|
||||
if [[ $TEST_SUITE != "behave" ]]; then
|
||||
echo Running unit tests using python${pv}
|
||||
$TEST_SUITE test
|
||||
unbuffer $TEST_SUITE test
|
||||
$TEST_SUITE flake8
|
||||
elif [[ $pv != "3.4" ]]; then
|
||||
elif [[ $pv != $EXCLUDE_BEHAVE ]]; then
|
||||
echo Running acceptance tests using python${pv}
|
||||
if ! PATH=.:/usr/lib/postgresql/9.6/bin:$PATH $TEST_SUITE; then
|
||||
if ! PATH=.:/usr/lib/postgresql/9.6/bin:$PATH unbuffer $TEST_SUITE; then
|
||||
# output all log files when tests are failing
|
||||
grep . features/output/*/*postgres?.*
|
||||
grep . features/output/*_failed/*postgres?.*
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
@@ -110,5 +149,9 @@ script:
|
||||
|
||||
set +e
|
||||
after_success:
|
||||
# before_cache is executed earlier than after_success, so we need to restore one of virtualenv directories
|
||||
- fpv=$(basename $(readlink $HOME/virtualenv/python3.6)) && mv $HOME/mycache/${fpv} $HOME/virtualenv/${fpv}
|
||||
- coveralls
|
||||
- if [[ $TEST_SUITE != "behave" ]]; then python-codacy-coverage -r coverage.xml; fi
|
||||
- if [[ $DCS == "exhibitor" ]]; then ~/mycache/zookeeper-${ZKVERSION}/bin/zkServer.sh stop; fi
|
||||
- sudo kill $(jobs -p)
|
||||
|
||||
-13
@@ -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
|
||||
+145
-31
@@ -1,44 +1,158 @@
|
||||
## This Dockerfile is meant to aid in the building and debugging patroni whilst developing on your local machine
|
||||
## It has all the necessary components to play/debug with a single node appliance, running etcd
|
||||
FROM postgres:9.6
|
||||
MAINTAINER Alexander Kukushkin <[email protected]>
|
||||
ARG PG_MAJOR=10
|
||||
ARG COMPRESS=false
|
||||
ARG PGHOME=/home/postgres
|
||||
ARG PGDATA=$PGHOME/data
|
||||
ARG LC_ALL=C.UTF-8
|
||||
ARG LANG=C.UTF-8
|
||||
|
||||
RUN echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \
|
||||
FROM postgres:$PG_MAJOR as builder
|
||||
|
||||
ARG PGHOME
|
||||
ARG PGDATA
|
||||
ARG LC_ALL
|
||||
ARG LANG
|
||||
|
||||
ENV ETCDVERSION=2.3.8 CONFDVERSION=0.16.0
|
||||
|
||||
RUN set -ex \
|
||||
&& export DEBIAN_FRONTEND=noninteractive \
|
||||
&& echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \
|
||||
&& apt-get update -y \
|
||||
&& apt-get upgrade -y \
|
||||
&& apt-get install -y curl jq haproxy python-psycopg2 python-yaml python-requests \
|
||||
python-six python-dateutil python-urllib3 python-dnspython \
|
||||
python-pip python-setuptools python-kazoo python-prettytable python-wheel python \
|
||||
|
||||
&& pip install python-etcd==0.4.3 python-consul==0.7.0 click tzlocal --upgrade \
|
||||
|
||||
&& mkdir -p /home/postgres \
|
||||
&& chown postgres:postgres /home/postgres \
|
||||
|
||||
# Clean up
|
||||
&& apt-get remove -y python-pip python-setuptools \
|
||||
# postgres:10 is based on debian, which has the patroni package. We will install all required dependencies
|
||||
&& apt-cache depends patroni | sed -n -e 's/.*Depends: \(python3-.\+\)$/\1/p' \
|
||||
| grep -Ev '^python3-(sphinx|etcd|consul|kazoo|kubernetes)' \
|
||||
| xargs apt-get install -y vim curl less jq locales haproxy sudo \
|
||||
python3-etcd python3-kazoo python3-pip busybox \
|
||||
net-tools iputils-ping --fix-missing \
|
||||
&& pip3 install dumb-init \
|
||||
\
|
||||
# Cleanup all locales but en_US.UTF-8
|
||||
&& find /usr/share/i18n/charmaps/ -type f ! -name UTF-8.gz -delete \
|
||||
&& find /usr/share/i18n/locales/ -type f ! -name en_US ! -name en_GB ! -name i18n* ! -name iso14651_t1 ! -name iso14651_t1_common ! -name 'translit_*' -delete \
|
||||
&& echo 'en_US.UTF-8 UTF-8' > /usr/share/i18n/SUPPORTED \
|
||||
\
|
||||
# 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 \
|
||||
\
|
||||
# haproxy dummy config
|
||||
&& echo 'global\n stats socket /run/haproxy/admin.sock mode 660 level admin' > /etc/haproxy/haproxy.cfg \
|
||||
\
|
||||
# vim config
|
||||
&& echo 'syntax on\nfiletype plugin indent on\nset mouse-=a\nautocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab' > /etc/vim/vimrc.local \
|
||||
\
|
||||
# Prepare postgres/patroni/haproxy environment
|
||||
&& mkdir -p $PGHOME/.config/patroni /patroni /run/haproxy \
|
||||
&& ln -s ../../postgres0.yml $PGHOME/.config/patroni/patronictl.yaml \
|
||||
&& ln -s /patronictl.py /usr/local/bin/patronictl \
|
||||
&& sed -i "s|/var/lib/postgresql.*|$PGHOME:/bin/bash|" /etc/passwd \
|
||||
&& chown -R postgres:postgres /var/log \
|
||||
\
|
||||
# Download etcd
|
||||
&& curl -sL https://github.com/coreos/etcd/releases/download/v${ETCDVERSION}/etcd-v${ETCDVERSION}-linux-amd64.tar.gz \
|
||||
| tar xz -C /usr/local/bin --strip=1 --wildcards --no-anchored etcd etcdctl \
|
||||
\
|
||||
# Download confd
|
||||
&& curl -sL https://github.com/kelseyhightower/confd/releases/download/v${CONFDVERSION}/confd-${CONFDVERSION}-linux-amd64 \
|
||||
> /usr/local/bin/confd && chmod +x /usr/local/bin/confd \
|
||||
\
|
||||
# Clean up all useless packages and some files
|
||||
&& apt-get purge -y --allow-remove-essential python3-pip gzip bzip2 util-linux e2fsprogs \
|
||||
libmagic1 bsdmainutils login ncurses-bin libmagic-mgc e2fslibs bsdutils \
|
||||
exim4-config gnupg-agent dirmngr libpython2.7-stdlib libpython2.7-minimal \
|
||||
&& apt-get autoremove -y \
|
||||
&& apt-get clean -y \
|
||||
&& rm -rf /var/lib/apt/lists/* /root/.cache
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
/root/.cache \
|
||||
/var/cache/debconf/* \
|
||||
/etc/rc?.d \
|
||||
/etc/systemd \
|
||||
/docker-entrypoint* \
|
||||
/sbin/pam* \
|
||||
/sbin/swap* \
|
||||
/sbin/unix* \
|
||||
/usr/local/bin/gosu \
|
||||
/usr/sbin/[acgipr]* \
|
||||
/usr/sbin/*user* \
|
||||
/usr/share/doc* \
|
||||
/usr/share/man \
|
||||
/usr/share/info \
|
||||
/usr/share/i18n/locales/translit_hangul \
|
||||
/usr/share/locale/?? \
|
||||
/usr/share/locale/??_?? \
|
||||
/usr/share/postgresql/*/man \
|
||||
/usr/share/postgresql-common/pg_wrapper \
|
||||
/usr/share/vim/vim80/doc \
|
||||
/usr/share/vim/vim80/lang \
|
||||
/usr/share/vim/vim80/tutor \
|
||||
# /var/lib/dpkg/info/* \
|
||||
&& find /usr/bin -xtype l -delete \
|
||||
&& find /var/log -type f -exec truncate --size 0 {} \; \
|
||||
&& find /usr/lib/python3/dist-packages -name '*test*' | xargs rm -fr \
|
||||
&& find /lib/x86_64-linux-gnu/security -type f ! -name pam_env.so ! -name pam_permit.so ! -name pam_unix.so -delete
|
||||
|
||||
ENV ETCDVERSION 3.1.2
|
||||
RUN curl -L https://github.com/coreos/etcd/releases/download/v${ETCDVERSION}/etcd-v${ETCDVERSION}-linux-amd64.tar.gz \
|
||||
| tar xz -C /usr/local/bin --strip=1 --wildcards --no-anchored etcd etcdctl
|
||||
# perform compression if it is necessary
|
||||
ARG COMPRESS
|
||||
RUN if [ "$COMPRESS" = "true" ]; then \
|
||||
set -ex \
|
||||
# Allow certain sudo commands from postgres
|
||||
&& echo 'postgres ALL=(ALL) NOPASSWD: /bin/tar xpJf /a.tar.xz -C /, /bin/rm /a.tar.xz, /bin/ln -snf dash /bin/sh' >> /etc/sudoers \
|
||||
&& ln -snf busybox /bin/sh \
|
||||
&& files="/bin/sh /usr/bin/sudo /usr/lib/sudo/sudoers.so /lib/x86_64-linux-gnu/security/pam_*.so" \
|
||||
&& libs="$(ldd $files | awk '{print $3;}' | grep '^/' | sort -u) /lib/x86_64-linux-gnu/ld-linux-x86-64.so.* /lib/x86_64-linux-gnu/libnsl.so.* /lib/x86_64-linux-gnu/libnss_compat.so.*" \
|
||||
&& (echo /var/run $files $libs | tr ' ' '\n' && realpath $files $libs) | sort -u | sed 's/^\///' > /exclude \
|
||||
&& find /etc/alternatives -xtype l -delete \
|
||||
&& save_dirs="usr lib var bin sbin etc/ssl etc/init.d etc/alternatives etc/apt" \
|
||||
&& XZ_OPT=-e9v tar -X /exclude -cpJf a.tar.xz $save_dirs \
|
||||
# we call "cat /exclude" to avoid including files from the $save_dirs that are also among
|
||||
# the exceptions listed in the /exclude, as "uniq -u" eliminates all non-unique lines.
|
||||
# By calling "cat /exclude" a second time we guarantee that there will be at least two lines
|
||||
# for each exception and therefore they will be excluded from the output passed to 'rm'.
|
||||
&& /bin/busybox sh -c "(find $save_dirs -not -type d && cat /exclude /exclude && echo exclude) | sort | uniq -u | xargs /bin/busybox rm" \
|
||||
&& /bin/busybox --install -s \
|
||||
&& /bin/busybox sh -c "find $save_dirs -type d -depth -exec rmdir -p {} \; 2> /dev/null"; \
|
||||
fi
|
||||
|
||||
ENV CONFDVERSION 0.11.0
|
||||
RUN curl -L https://github.com/kelseyhightower/confd/releases/download/v${CONFDVERSION}/confd-${CONFDVERSION}-linux-amd64 > /usr/local/bin/confd \
|
||||
&& chmod +x /usr/local/bin/confd
|
||||
FROM scratch
|
||||
COPY --from=builder / /
|
||||
|
||||
ADD patronictl.py patroni.py docker/entrypoint.sh /
|
||||
ADD patroni /patroni/
|
||||
ADD extras/confd /etc/confd
|
||||
RUN ln -s /patronictl.py /usr/local/bin/patronictl
|
||||
LABEL maintainer="Alexander Kukushkin <[email protected]>"
|
||||
|
||||
### Setting up a simple script that will serve as an entrypoint
|
||||
RUN mkdir /data/ && touch /pgpass /patroni.yml \
|
||||
&& chown postgres:postgres -R /patroni/ /data/ /pgpass /patroni.yml /etc/haproxy /var/run/ /var/lib/ /var/log/
|
||||
ARG PG_MAJOR
|
||||
ARG COMPRESS
|
||||
ARG PGHOME
|
||||
ARG PGDATA
|
||||
ARG LC_ALL
|
||||
ARG LANG
|
||||
|
||||
EXPOSE 2379 5432 8008
|
||||
ARG PGBIN=/usr/lib/postgresql/$PG_MAJOR/bin
|
||||
|
||||
ENV LC_ALL=$LC_ALL LANG=$LANG EDITOR=/usr/bin/editor
|
||||
ENV PGDATA=$PGDATA PATH=$PATH:$PGBIN
|
||||
|
||||
COPY patroni /patroni/
|
||||
COPY extras/confd/conf.d/haproxy.toml /etc/confd/conf.d/
|
||||
COPY extras/confd/templates/haproxy.tmpl /etc/confd/templates/
|
||||
COPY patroni*.py docker/entrypoint.sh /
|
||||
COPY postgres?.yml $PGHOME/
|
||||
|
||||
WORKDIR $PGHOME
|
||||
|
||||
RUN sed -i 's/env python/&3/' /patroni*.py \
|
||||
# "fix" patroni configs
|
||||
&& sed -i 's/^\( connect_address:\| - host\)/#&/' postgres?.yml \
|
||||
&& sed -i 's/^ listen: 127.0.0.1/ listen: 0.0.0.0/' postgres?.yml \
|
||||
&& sed -i "s|^\( data_dir: \).*|\1$PGDATA|" postgres?.yml \
|
||||
&& sed -i "s|^#\( bin_dir: \).*|\1$PGBIN|" postgres?.yml \
|
||||
&& sed -i 's/^ - encoding: UTF8/ - locale: en_US.UTF-8\n&/' postgres?.yml \
|
||||
&& sed -i 's/^\(scope\|name\|etcd\| host\| authentication\| pg_hba\| parameters\):/#&/' postgres?.yml \
|
||||
&& sed -i 's/^ \(replication\|superuser\|rewind\|unix_socket_directories\|\(\( \)\{0,1\}\(username\|password\)\)\):/#&/' postgres?.yml \
|
||||
&& sed -i 's/^ parameters:/ pg_hba:\n - local all all trust\n - host replication all all md5\n - host all all all md5\n&\n max_connections: 100/' postgres?.yml \
|
||||
&& if [ "$COMPRESS" = "true" ]; then chmod u+s /usr/bin/sudo; fi \
|
||||
&& chmod +s /bin/ping \
|
||||
&& chown -R postgres:postgres $PGHOME /run /etc/haproxy
|
||||
|
||||
ENTRYPOINT ["/bin/bash", "/entrypoint.sh"]
|
||||
USER postgres
|
||||
|
||||
ENTRYPOINT ["/bin/sh", "/entrypoint.sh"]
|
||||
|
||||
+85
-22
@@ -1,27 +1,27 @@
|
||||
|Build Status| |Coverage Status|
|
||||
|
||||
Patroni: A Template for PostgreSQL HA with ZooKeeper, etcd or Consul
|
||||
------------------------------------------------------------
|
||||
--------------------------------------------------------------------
|
||||
|
||||
You can find a version of this documentation that is searchable and also easier to navigate at `patroni.readthedocs.io <https://patroni.readthedocs.io>`__.
|
||||
|
||||
|
||||
There are many ways to run high availability with PostgreSQL; for a list, see the `PostgreSQL Documentation <https://wiki.postgresql.org/wiki/Replication,_Clustering,_and_Connection_Pooling>`__.
|
||||
|
||||
Patroni is a template for you to create your own customized, high-availability solution using Python and - for maximum accessibility - a distributed configuration store like `ZooKeeper <https://zookeeper.apache.org/>`__, `etcd <https://github.com/coreos/etcd>`__ or `Consul <https://github.com/hashicorp/consul>`__. Database engineers, DBAs, DevOps engineers, and SREs who are looking to quickly deploy HA PostgreSQL in the datacenter-or anywhere else-will hopefully find it useful.
|
||||
Patroni is a template for you to create your own customized, high-availability solution using Python and - for maximum accessibility - a distributed configuration store like `ZooKeeper <https://zookeeper.apache.org/>`__, `etcd <https://github.com/coreos/etcd>`__, `Consul <https://github.com/hashicorp/consul>`__ or `Kubernetes <https://kubernetes.io>`__. Database engineers, DBAs, DevOps engineers, and SREs who are looking to quickly deploy HA PostgreSQL in the datacenter-or anywhere else-will hopefully find it useful.
|
||||
|
||||
We call Patroni a "template" because it is far from being a one-size-fits-all or plug-and-play replication system. It will have its own caveats. Use wisely.
|
||||
|
||||
**Note to Kubernetes users**: We're currently developing Patroni to be as useful as possible for teams running Kubernetes on top of Google Compute Engine; Patroni can be the HA solution for Postgres in such an environment. To this end, there is a `Helm chart <https://github.com/kubernetes/charts/tree/master/incubator/patroni>`__ that uses Patroni and `Spilo <https://github.com/zalando/spilo/>`__ to provision a five-node PostgreSQL HA cluster in a Kubernetes+GCE environment. (The Helm chart deploys Spilo Docker images, not just "bare" Patroni.)
|
||||
**Note to Kubernetes users**: Patroni can run natively on top of Kubernetes. Take a look at the `Kubernetes <https://github.com/zalando/patroni/blob/master/docs/kubernetes.rst>`__ chapter of the Patroni documentation.
|
||||
|
||||
.. contents::
|
||||
:local:
|
||||
:depth: 1
|
||||
:backlinks: none
|
||||
|
||||
==============
|
||||
=================
|
||||
How Patroni Works
|
||||
==============
|
||||
=================
|
||||
|
||||
Patroni originated as a fork of `Governor <https://github.com/compose/governor>`__, the project from Compose. It includes plenty of new features.
|
||||
|
||||
@@ -29,39 +29,102 @@ For an example of a Docker-based deployment with Patroni, see `Spilo <https://gi
|
||||
|
||||
For additional background info, see:
|
||||
|
||||
* `Elephants on Automatic: HA Clustered PostgreSQL with Helm <https://www.youtube.com/watch?v=CftcVhFMGSY>`_, talk by Josh Berkus and Oleksii Kliukin at KubeCon Berlin 2017
|
||||
* `Elephants on Automatic: HA Clustered PostgreSQL with Helm <https://www.youtube.com/watch?v=CftcVhFMGSY>`_, talk by Josh Berkus and Oleksii Kliukin at KubeCon Berlin 2017
|
||||
* `PostgreSQL HA with Kubernetes and Patroni <https://www.youtube.com/watch?v=iruaCgeG7qs>`__, talk by Josh Berkus at KubeCon 2016 (video)
|
||||
* `Feb. 2016 Zalando Tech blog post <https://tech.zalando.de/blog/zalandos-patroni-a-template-for-high-availability-postgresql/>`__
|
||||
|
||||
================
|
||||
==================
|
||||
Development Status
|
||||
================
|
||||
==================
|
||||
|
||||
Patroni is in active development and accepts contributions. See our `Contributing <https://github.com/zalando/patroni/blob/master/docs/CONTRIBUTING.rst>`__ section below for more details.
|
||||
|
||||
We report new releases information `here <https://github.com/zalando/patroni/releases>`__.
|
||||
|
||||
===========================
|
||||
Technical Requirements/Installation
|
||||
===========================
|
||||
=========
|
||||
Community
|
||||
=========
|
||||
|
||||
**For Mac**
|
||||
There are two places to connect with the Patroni community: `on github <https://github.com/zalando/patroni>`__, via Issues and PRs, and on channel #patroni in the `PostgreSQL Slack <https://postgres-slack.herokuapp.com/>`__. If you're using Patroni, or just interested, please join us.
|
||||
|
||||
===================================
|
||||
Technical Requirements/Installation
|
||||
===================================
|
||||
|
||||
**Pre-requirements for Mac OS**
|
||||
|
||||
To install requirements on a Mac, run the following:
|
||||
|
||||
::
|
||||
|
||||
brew install postgresql etcd haproxy libyaml python
|
||||
pip install psycopg2 pyyaml
|
||||
|
||||
===================
|
||||
**Psycopg2**
|
||||
|
||||
Starting from `psycopg2-2.8 <http://initd.org/psycopg/articles/2019/04/04/psycopg-28-released/>`__ the binary version of psycopg2 will no longer be installed by default. Installing it from the source code requires C compiler and postgres+python dev packages.
|
||||
Since in the python world it is not possible to specify dependency as ``psycopg2 OR psycopg2-binary`` you will have to decide how to install it.
|
||||
|
||||
There are a few options available:
|
||||
|
||||
1. Use the package manager from your distro
|
||||
|
||||
::
|
||||
|
||||
sudo apt-get install python-psycopg2 # install python2 psycopg2 module on Debian/Ubuntu
|
||||
sudo apt-get install python3-psycopg2 # install python3 psycopg2 module on Debian/Ubuntu
|
||||
sudo yum install python-psycopg2 # install python2 psycopg2 on RedHat/Fedora/CentOS
|
||||
|
||||
2. Install psycopg2 from the binary package
|
||||
|
||||
::
|
||||
|
||||
pip install psycopg2-binary
|
||||
|
||||
3. Install psycopg2 from source
|
||||
|
||||
::
|
||||
|
||||
pip install psycopg2>=2.5.4
|
||||
|
||||
**General installation for pip**
|
||||
|
||||
Patroni can be installed with pip:
|
||||
|
||||
::
|
||||
|
||||
pip install patroni[dependencies]
|
||||
|
||||
where dependencies can be either empty, or consist of one or more of the following:
|
||||
|
||||
etcd
|
||||
`python-etcd` module in order to use Etcd as DCS
|
||||
consul
|
||||
`python-consul` module in order to use Consul as DCS
|
||||
zookeeper
|
||||
`kazoo` module in order to use Zookeeper as DCS
|
||||
exhibitor
|
||||
`kazoo` module in order to use Exhibitor as DCS (same dependencies as for Zookeeper)
|
||||
kubernetes
|
||||
`kubernetes` module in order to use Kubernetes as DCS in Patroni
|
||||
aws
|
||||
`boto` in order to use AWS callbacks
|
||||
|
||||
For example, the command in order to install Patroni together with dependencies for Etcd as a DCS and AWS callbacks is:
|
||||
|
||||
::
|
||||
|
||||
pip install patroni[etcd,aws]
|
||||
|
||||
Note that external tools to call in the replica creation or custom bootstap scripts (i.e. WAL-E) should be installed independently of Patroni.
|
||||
|
||||
=======================
|
||||
Running and Configuring
|
||||
===================
|
||||
=======================
|
||||
|
||||
To get started, do the following from different terminals:
|
||||
::
|
||||
|
||||
> etcd --data-dir=data/etcd
|
||||
> etcd --data-dir=data/etcd --enable-v2=true
|
||||
> ./patroni.py postgres0.yml
|
||||
> ./patroni.py postgres1.yml
|
||||
|
||||
@@ -80,9 +143,9 @@ run:
|
||||
|
||||
> psql --host 127.0.0.1 --port 5000 postgres
|
||||
|
||||
===============
|
||||
==================
|
||||
YAML Configuration
|
||||
===============
|
||||
==================
|
||||
|
||||
Go `here <https://github.com/zalando/patroni/blob/master/docs/SETTINGS.rst>`__ for comprehensive information about settings for etcd, consul, and ZooKeeper. And for an example, see `postgres0.yml <https://github.com/zalando/patroni/blob/master/postgres0.yml>`__.
|
||||
|
||||
@@ -92,15 +155,15 @@ Environment Configuration
|
||||
|
||||
Go `here <https://github.com/zalando/patroni/blob/master/docs/ENVIRONMENT.rst>`__ for comprehensive information about configuring(overriding) settings via environment variables.
|
||||
|
||||
===============
|
||||
===================
|
||||
Replication Choices
|
||||
===============
|
||||
===================
|
||||
|
||||
Patroni uses Postgres' streaming replication, which is asynchronous by default. Patroni's asynchronous replication configuration allows for ``maximum_lag_on_failover`` settings. This setting ensures failover will not occur if a follower is more than a certain number of bytes behind the leader. This setting should be increased or decreased based on business requirements. It's also possible to use synchronous replication for better durability guarantees. See `replication modes documentation <https://github.com/zalando/patroni/blob/master/docs/replication_modes.rst>`__ for details.
|
||||
|
||||
===============================
|
||||
======================================
|
||||
Applications Should Not Use Superusers
|
||||
===============================
|
||||
======================================
|
||||
|
||||
When connecting from an application, always use a non-superuser. Patroni requires access to the database to function properly. By using a superuser from an application, you can potentially use the entire connection pool, including the connections reserved for superusers, with the ``superuser_reserved_connections`` setting. If Patroni cannot access the Primary because the connection pool is full, behavior will be undesirable.
|
||||
|
||||
|
||||
+63
-52
@@ -1,58 +1,69 @@
|
||||
# docker compose file for running a 3-node PostgreSQL cluster
|
||||
# with etcd as the SIS
|
||||
# with 3-node etcd cluster as the DCS and one haproxy node
|
||||
version: "2"
|
||||
|
||||
patroni_etcd:
|
||||
container_name: patroni_etcd
|
||||
image: patroni
|
||||
command: --etcd
|
||||
networks:
|
||||
demo:
|
||||
|
||||
dbnode1:
|
||||
image: patroni
|
||||
hostname: dbnode1
|
||||
links:
|
||||
- patroni_etcd:patroni_etcd
|
||||
volumes:
|
||||
- ./patroni:/patroni
|
||||
env_file: docker/patroni-secrets.env
|
||||
environment:
|
||||
PATRONI_ETCD_HOST: patroni_etcd:2379
|
||||
PATRONI_NAME: dbnode1
|
||||
PATRONI_SCOPE: testcluster
|
||||
services:
|
||||
etcd1:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/etcd.env
|
||||
container_name: demo-etcd1
|
||||
hostname: etcd1
|
||||
command: etcd -name etcd1 -initial-advertise-peer-urls http://etcd1:2380
|
||||
|
||||
dbnode2:
|
||||
image: patroni
|
||||
hostname: dbnode2
|
||||
links:
|
||||
- patroni_etcd:patroni_etcd
|
||||
volumes:
|
||||
- ./patroni:/patroni
|
||||
env_file: docker/patroni-secrets.env
|
||||
environment:
|
||||
PATRONI_ETCD_HOST: patroni_etcd:2379
|
||||
PATRONI_NAME: dbnode2
|
||||
PATRONI_SCOPE: testcluster
|
||||
etcd2:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/etcd.env
|
||||
container_name: demo-etcd2
|
||||
hostname: etcd2
|
||||
command: etcd -name etcd2 -initial-advertise-peer-urls http://etcd2:2380
|
||||
|
||||
dbnode3:
|
||||
image: patroni
|
||||
hostname: dbnode3
|
||||
links:
|
||||
- patroni_etcd:patroni_etcd
|
||||
volumes:
|
||||
- ./patroni:/patroni
|
||||
env_file: docker/patroni-secrets.env
|
||||
environment:
|
||||
PATRONI_ETCD_HOST: patroni_etcd:2379
|
||||
PATRONI_NAME: dbnode3
|
||||
PATRONI_SCOPE: testcluster
|
||||
etcd3:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/etcd.env
|
||||
container_name: demo-etcd3
|
||||
hostname: etcd3
|
||||
command: etcd -name etcd3 -initial-advertise-peer-urls http://etcd3:2380
|
||||
|
||||
haproxy:
|
||||
image: patroni
|
||||
links:
|
||||
- patroni_etcd:patroni_etcd
|
||||
ports:
|
||||
- "5000:5000"
|
||||
- "5001:5001"
|
||||
environment:
|
||||
PATRONI_ETCD_HOST: patroni_etcd:2379
|
||||
PATRONI_SCOPE: testcluster
|
||||
command: --confd
|
||||
patroni1:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/patroni.env
|
||||
hostname: patroni1
|
||||
container_name: demo-patroni1
|
||||
environment:
|
||||
PATRONI_NAME: patroni1
|
||||
|
||||
patroni2:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/patroni.env
|
||||
hostname: patroni2
|
||||
container_name: demo-patroni2
|
||||
environment:
|
||||
PATRONI_NAME: patroni2
|
||||
|
||||
patroni3:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/patroni.env
|
||||
hostname: patroni3
|
||||
container_name: demo-patroni3
|
||||
environment:
|
||||
PATRONI_NAME: patroni3
|
||||
|
||||
haproxy:
|
||||
image: patroni
|
||||
networks: [ demo ]
|
||||
env_file: docker/patroni.env
|
||||
hostname: haproxy
|
||||
container_name: demo-haproxy
|
||||
ports:
|
||||
- "5000:5000"
|
||||
- "5001:5001"
|
||||
command: haproxy
|
||||
|
||||
+103
-33
@@ -1,47 +1,117 @@
|
||||
# Patroni Dockerfile
|
||||
You can run Patroni in a docker container using this Dockerfile, or by using one of the Docker image at
|
||||
|
||||
https://registry.opensource.zalan.do/v1/repositories/acid/patroni/tags
|
||||
You can run Patroni in a docker container using this Dockerfile
|
||||
|
||||
This Dockerfile is meant in aiding development of Patroni and quick testing of features. It is not a production-worthy
|
||||
Dockerfile
|
||||
|
||||
docker build -t patroni .
|
||||
|
||||
# Examples
|
||||
|
||||
## Standalone Patroni
|
||||
|
||||
docker run -d registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT
|
||||
docker run -d patroni
|
||||
|
||||
## Multiple Patroni's communicating with a standalone etcd inside Docker
|
||||
|
||||
Basically what you would do would be:
|
||||
|
||||
* Run 1 container which provides etcd
|
||||
|
||||
docker run -d <IMAGE> --etcd-only
|
||||
|
||||
* Run n containers running Patroni, passing the `--etcd` option to the `docker run` command
|
||||
|
||||
docker run -d <IMAGE> --etcd=<IP FROM etcd CONTAINER:PORT>
|
||||
|
||||
To automate this you can run the following script:
|
||||
|
||||
dev_patroni_cluster.sh [OPTIONS]
|
||||
|
||||
Options:
|
||||
|
||||
--image IMAGE The Docker image to use for the cluster
|
||||
--members INT The number of members for the cluster
|
||||
--name NAME The name of the new cluster
|
||||
## Three-node Patroni cluster with three-node etcd cluster and one haproxy container using docker-compose
|
||||
|
||||
Example session:
|
||||
|
||||
$ ./dev_patroni_cluster.sh --image registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT --members=2 --name=bravo
|
||||
The etcd container is 6be871a11cb373406ca5ea1c6b39e1.0-SNAPSHOTfdde9fb1d6177212d6ad0c0d1bd9b563, ip=172.17.1.24
|
||||
Started Patroni container 67e611f2eca7c40f9e6e0e24a4a8f2cba7e3e56d22a420e15ab9240a37a9d7a4, ip=172.17.1.25
|
||||
Started Patroni container 47dd12ae635ab83b039f5889e250048b606ed5e48e3650b69e365e7e1d4acbcf, ip=172.17.1.26
|
||||
$ docker-compose up -d
|
||||
Creating demo-haproxy ...
|
||||
Creating demo-patroni2 ...
|
||||
Creating demo-patroni1 ...
|
||||
Creating demo-patroni3 ...
|
||||
Creating demo-etcd2 ...
|
||||
Creating demo-etcd1 ...
|
||||
Creating demo-etcd3 ...
|
||||
Creating demo-haproxy
|
||||
Creating demo-patroni2
|
||||
Creating demo-patroni1
|
||||
Creating demo-patroni3
|
||||
Creating demo-etcd1
|
||||
Creating demo-etcd2
|
||||
Creating demo-etcd2 ... done
|
||||
|
||||
$ docker ps
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
47dd12ae635a registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT "/bin/bash /entrypoi 10 seconds ago Up 8 seconds 4001/tcp, 5432/tcp, 2380/tcp bravo_OR64g8bx
|
||||
67e611f2eca7 registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT "/bin/bash /entrypoi 11 seconds ago Up 10 seconds 2380/tcp, 4001/tcp, 5432/tcp bravo_si9no8iz
|
||||
6be871a11cb3 registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT "/bin/bash /entrypoi 12 seconds ago Up 10 seconds 4001/tcp, 5432/tcp, 2380/tcp bravo_etcd
|
||||
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
|
||||
5b7a90b4cfbf patroni "/bin/sh /entrypoint…" 29 seconds ago Up 27 seconds demo-etcd2
|
||||
e30eea5222f2 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 27 seconds demo-etcd1
|
||||
83bcf3cb208f patroni "/bin/sh /entrypoint…" 29 seconds ago Up 27 seconds demo-etcd3
|
||||
922532c56e7d patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds demo-patroni3
|
||||
14f875e445f3 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds demo-patroni2
|
||||
110d1073b383 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds demo-patroni1
|
||||
5af5e6e36028 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds 0.0.0.0:5000-5001->5000-5001/tcp demo-haproxy
|
||||
|
||||
$ docker logs demo-patroni1
|
||||
2019-02-20 08:19:32,714 INFO: Failed to import patroni.dcs.consul
|
||||
2019-02-20 08:19:32,737 INFO: Selected new etcd server http://etcd3:2379
|
||||
2019-02-20 08:19:35,140 INFO: Lock owner: None; I am patroni1
|
||||
2019-02-20 08:19:35,174 INFO: trying to bootstrap a new cluster
|
||||
...
|
||||
2019-02-20 08:19:39,310 INFO: postmaster pid=37
|
||||
2019-02-20 08:19:39.314 UTC [37] LOG: listening on IPv4 address "0.0.0.0", port 5432
|
||||
2019-02-20 08:19:39.321 UTC [37] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
|
||||
2019-02-20 08:19:39.353 UTC [39] LOG: database system was shut down at 2019-02-20 08:19:36 UTC
|
||||
2019-02-20 08:19:39.354 UTC [40] FATAL: the database system is starting up
|
||||
localhost:5432 - rejecting connections
|
||||
2019-02-20 08:19:39.369 UTC [37] LOG: database system is ready to accept connections
|
||||
localhost:5432 - accepting connections
|
||||
2019-02-20 08:19:39,383 INFO: establishing a new patroni connection to the postgres cluster
|
||||
2019-02-20 08:19:39,408 INFO: running post_bootstrap
|
||||
2019-02-20 08:19:39,432 WARNING: Could not activate Linux watchdog device: "Can't open watchdog device: [Errno 2] No such file or directory: '/dev/watchdog'"
|
||||
2019-02-20 08:19:39,515 INFO: initialized a new cluster
|
||||
2019-02-20 08:19:49,424 INFO: Lock owner: patroni1; I am patroni1
|
||||
2019-02-20 08:19:49,447 INFO: Lock owner: patroni1; I am patroni1
|
||||
2019-02-20 08:19:49,480 INFO: no action. i am the leader with the lock
|
||||
2019-02-20 08:19:59,422 INFO: Lock owner: patroni1; I am patroni1
|
||||
|
||||
$ docker exec -ti demo-patroni1 bash
|
||||
postgres@patroni1:~$ patronictl list
|
||||
+---------+----------+------------+--------+---------+----+-----------+
|
||||
| Cluster | Member | Host | Role | State | TL | Lag in MB |
|
||||
+---------+----------+------------+--------+---------+----+-----------+
|
||||
| demo | patroni1 | 172.22.0.3 | Leader | running | 1 | 0 |
|
||||
| demo | patroni2 | 172.22.0.7 | | running | 1 | 0 |
|
||||
| demo | patroni3 | 172.22.0.4 | | running | 1 | 0 |
|
||||
+---------+----------+------------+--------+---------+----+-----------+
|
||||
|
||||
postgres@patroni1:~$ etcdctl ls --recursive --sort -p /service/demo
|
||||
/service/demo/config
|
||||
/service/demo/initialize
|
||||
/service/demo/leader
|
||||
/service/demo/members/
|
||||
/service/demo/members/patroni1
|
||||
/service/demo/members/patroni2
|
||||
/service/demo/members/patroni3
|
||||
/service/demo/optime/
|
||||
/service/demo/optime/leader
|
||||
|
||||
postgres@patroni1:~$ etcdctl member list
|
||||
1bab629f01fa9065: name=etcd3 peerURLs=http://etcd3:2380 clientURLs=http://etcd3:2379 isLeader=false
|
||||
8ecb6af518d241cc: name=etcd2 peerURLs=http://etcd2:2380 clientURLs=http://etcd2:2379 isLeader=true
|
||||
b2e169fcb8a34028: name=etcd1 peerURLs=http://etcd1:2380 clientURLs=http://etcd1:2379 isLeader=false
|
||||
postgres@patroni1:~$ exit
|
||||
|
||||
$ psql -h localhost -p 5000 -U postgres -W
|
||||
Password: postgres
|
||||
psql (11.2 (Ubuntu 11.2-1.pgdg18.04+1), server 10.7 (Debian 10.7-1.pgdg90+1))
|
||||
Type "help" for help.
|
||||
|
||||
localhost/postgres=# select pg_is_in_recovery();
|
||||
pg_is_in_recovery
|
||||
───────────────────
|
||||
f
|
||||
(1 row)
|
||||
|
||||
localhost/postgres=# \q
|
||||
|
||||
$ psql -h localhost -p 5001 -U postgres -W
|
||||
Password: postgres
|
||||
psql (11.2 (Ubuntu 11.2-1.pgdg18.04+1), server 10.7 (Debian 10.7-1.pgdg90+1))
|
||||
Type "help" for help.
|
||||
|
||||
localhost/postgres=# select pg_is_in_recovery();
|
||||
pg_is_in_recovery
|
||||
───────────────────
|
||||
t
|
||||
(1 row)
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
DOCKER_IMAGE="registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT"
|
||||
MEMBERS=3
|
||||
|
||||
|
||||
function usage()
|
||||
{
|
||||
cat <<__EOF__
|
||||
Usage: $0
|
||||
|
||||
Options:
|
||||
|
||||
--image IMAGE The Docker image to use for the cluster
|
||||
--members INT The number of members for the cluster
|
||||
--name NAME The name of the new cluster
|
||||
|
||||
Examples:
|
||||
|
||||
$0 --image ${DOCKER_IMAGE}
|
||||
$0
|
||||
$0 --image ${DOCKER_IMAGE} --members=2
|
||||
__EOF__
|
||||
}
|
||||
|
||||
|
||||
optspec=":-:"
|
||||
while getopts "$optspec" optchar; do
|
||||
case "${optchar}" in
|
||||
-)
|
||||
case "${OPTARG}" in
|
||||
help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
name)
|
||||
PATRONI_SCOPE="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
|
||||
;;
|
||||
name=*)
|
||||
PATRONI_SCOPE="${OPTARG#*=}"
|
||||
;;
|
||||
image)
|
||||
DOCKER_IMAGE="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
|
||||
;;
|
||||
image=*)
|
||||
DOCKER_IMAGE="${OPTARG#*=}"
|
||||
;;
|
||||
members)
|
||||
MEMBERS="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
|
||||
;;
|
||||
members=*)
|
||||
MEMBERS="${OPTARG#*=}"
|
||||
;;
|
||||
*)
|
||||
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
|
||||
echo "Unknown option --${OPTARG}" >&2
|
||||
fi
|
||||
;;
|
||||
esac;;
|
||||
*)
|
||||
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
|
||||
echo "Non-option argument: '-${OPTARG}'" >&2
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z ${PATRONI_SCOPE} ]; then
|
||||
PATRONI_SCOPE=$(cat /dev/urandom | LC_ALL=C tr -dc 'a-z0-9' | head -c 8)
|
||||
fi
|
||||
|
||||
function docker_run()
|
||||
{
|
||||
local name=$1
|
||||
shift
|
||||
container=$(docker run -d --name=$name $*)
|
||||
container_ip=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${container})
|
||||
echo "Started container ${name}, ip=${container_ip}"
|
||||
}
|
||||
|
||||
|
||||
ETCD_CONTAINER="${PATRONI_SCOPE}_etcd"
|
||||
docker_run ${ETCD_CONTAINER} ${DOCKER_IMAGE} --etcd
|
||||
|
||||
DOCKER_ARGS="--link=${ETCD_CONTAINER}:${ETCD_CONTAINER} -e PATRONI_SCOPE=${PATRONI_SCOPE} -e PATRONI_ETCD_HOST=${ETCD_CONTAINER}:2379"
|
||||
PATRONI_ENV=$(sed 's/#.*//g' docker/patroni-secrets.env | sed -n 's/^PATRONI_.*$/-e &/p' | tr '\n' ' ')
|
||||
PATRONI_VOLUME="-v $(dirname $(dirname $(realpath $0)))/patroni:/patroni"
|
||||
|
||||
for i in $(seq 1 "${MEMBERS}"); do
|
||||
container_name=postgres${i}
|
||||
docker_run "${PATRONI_SCOPE}_${container_name}" \
|
||||
$PATRONI_VOLUME \
|
||||
$DOCKER_ARGS \
|
||||
$PATRONI_ENV \
|
||||
-e PATRONI_NAME=${container_name} \
|
||||
${DOCKER_IMAGE}
|
||||
done
|
||||
|
||||
docker_run "${PATRONI_SCOPE}_haproxy" \
|
||||
-p=5000 -p=5001 \
|
||||
$DOCKER_ARGS \
|
||||
${DOCKER_IMAGE} --confd
|
||||
+45
-100
@@ -1,115 +1,60 @@
|
||||
#!/bin/bash
|
||||
#!/bin/sh
|
||||
|
||||
function usage()
|
||||
{
|
||||
cat <<__EOF__
|
||||
Usage: $0
|
||||
if [ -f /a.tar.xz ]; then
|
||||
echo "decompressing image..."
|
||||
sudo tar xpJf /a.tar.xz -C / > /dev/null 2>&1
|
||||
sudo rm /a.tar.xz
|
||||
sudo ln -snf dash /bin/sh
|
||||
fi
|
||||
|
||||
Options:
|
||||
readonly PATRONI_SCOPE=${PATRONI_SCOPE:-batman}
|
||||
PATRONI_NAMESPACE=${PATRONI_NAMESPACE:-/service}
|
||||
readonly PATRONI_NAMESPACE=${PATRONI_NAMESPACE%/}
|
||||
readonly DOCKER_IP=$(hostname --ip-address)
|
||||
|
||||
--etcd Do not run Patroni, run a standalone etcd
|
||||
--confd Do not run Patroni, run a standalone confd
|
||||
--zookeeper Do not run Patroni, run a standalone zookeeper
|
||||
|
||||
Examples:
|
||||
|
||||
$0 --etcd
|
||||
$0 --confd
|
||||
$0 --zookeeper
|
||||
$0
|
||||
__EOF__
|
||||
}
|
||||
|
||||
DOCKER_IP=$(hostname --ip-address)
|
||||
PATRONI_SCOPE=${PATRONI_SCOPE:-batman}
|
||||
ETCD_ARGS="--data-dir /tmp/etcd.data -advertise-client-urls=http://${DOCKER_IP}:2379 -listen-client-urls=http://0.0.0.0:2379 -listen-peer-urls=http://0.0.0.0:2380"
|
||||
|
||||
optspec=":vh-:"
|
||||
while getopts "$optspec" optchar; do
|
||||
case "${optchar}" in
|
||||
-)
|
||||
case "${OPTARG}" in
|
||||
confd)
|
||||
haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -D
|
||||
CONFD="confd -prefix=${PATRONI_NAMESPACE:-/service}/$PATRONI_SCOPE -interval=10 -backend"
|
||||
if [ ! -z ${PATRONI_ZOOKEEPER_HOSTS} ]; then
|
||||
while ! /usr/share/zookeeper/bin/zkCli.sh -server ${PATRONI_ZOOKEEPER_HOSTS} ls /; do
|
||||
sleep 1
|
||||
done
|
||||
exec $CONFD zookeeper -node ${PATRONI_ZOOKEEPER_HOSTS}
|
||||
else
|
||||
while ! curl -s ${PATRONI_ETCD_HOST}/v2/members | jq -r '.members[0].clientURLs[0]' | grep -q http; do
|
||||
sleep 1
|
||||
done
|
||||
exec $CONFD etcd -node $PATRONI_ETCD_HOST
|
||||
fi
|
||||
;;
|
||||
etcd)
|
||||
exec etcd $ETCD_ARGS
|
||||
;;
|
||||
zookeeper)
|
||||
exec /usr/share/zookeeper/bin/zkServer.sh start-foreground
|
||||
;;
|
||||
cheat)
|
||||
CHEAT=1
|
||||
;;
|
||||
help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
|
||||
echo "Unknown option --${OPTARG}" >&2
|
||||
fi
|
||||
;;
|
||||
esac;;
|
||||
*)
|
||||
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
|
||||
echo "Non-option argument: '-${OPTARG}'" >&2
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
case "$1" in
|
||||
haproxy)
|
||||
haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -D
|
||||
CONFD="confd -prefix=$PATRONI_NAMESPACE/$PATRONI_SCOPE -interval=10 -backend"
|
||||
if [ ! -z "$PATRONI_ZOOKEEPER_HOSTS" ]; then
|
||||
while ! /usr/share/zookeeper/bin/zkCli.sh -server $PATRONI_ZOOKEEPER_HOSTS ls /; do
|
||||
sleep 1
|
||||
done
|
||||
exec dumb-init $CONFD zookeeper -node $PATRONI_ZOOKEEPER_HOSTS
|
||||
else
|
||||
while ! etcdctl cluster-health 2> /dev/null; do
|
||||
sleep 1
|
||||
done
|
||||
exec dumb-init $CONFD etcd -node $(echo $ETCDCTL_ENDPOINTS | sed 's/,/ -node /g')
|
||||
fi
|
||||
;;
|
||||
etcd)
|
||||
exec "$@" -advertise-client-urls http://$DOCKER_IP:2379
|
||||
;;
|
||||
zookeeper)
|
||||
exec /usr/share/zookeeper/bin/zkServer.sh start-foreground
|
||||
;;
|
||||
esac
|
||||
|
||||
## We start an etcd
|
||||
if [[ -z ${PATRONI_ETCD_HOST} && -z ${PATRONI_ZOOKEEPER_HOSTS} ]]; then
|
||||
etcd $ETCD_ARGS > /var/log/etcd.log 2> /var/log/etcd.err &
|
||||
export PATRONI_ETCD_HOST="127.0.0.1:2379"
|
||||
if [ -z "$PATRONI_ETCD_HOSTS" ] && [ -z "$PATRONI_ZOOKEEPER_HOSTS" ]; then
|
||||
export PATRONI_ETCD_URL="http://127.0.0.1:2379"
|
||||
etcd --data-dir /tmp/etcd.data -advertise-client-urls=$PATRONI_ETCD_URL -listen-client-urls=http://0.0.0.0:2379 > /var/log/etcd.log 2> /var/log/etcd.err &
|
||||
fi
|
||||
|
||||
export PATRONI_SCOPE
|
||||
export PATRONI_NAME="${PATRONI_NAME:-${HOSTNAME}}"
|
||||
export PATRONI_RESTAPI_CONNECT_ADDRESS="${DOCKER_IP}:8008"
|
||||
export PATRONI_NAMESPACE
|
||||
export PATRONI_NAME="${PATRONI_NAME:-$(hostname)}"
|
||||
export PATRONI_RESTAPI_CONNECT_ADDRESS="$DOCKER_IP:8008"
|
||||
export PATRONI_RESTAPI_LISTEN="0.0.0.0:8008"
|
||||
export PATRONI_admin_PASSWORD="${PATRONI_admin_PASSWORD:=admin}"
|
||||
export PATRONI_admin_PASSWORD="${PATRONI_admin_PASSWORD:-admin}"
|
||||
export PATRONI_admin_OPTIONS="${PATRONI_admin_OPTIONS:-createdb, createrole}"
|
||||
export PATRONI_POSTGRESQL_CONNECT_ADDRESS="${DOCKER_IP}:5432"
|
||||
export PATRONI_POSTGRESQL_CONNECT_ADDRESS="$DOCKER_IP:5432"
|
||||
export PATRONI_POSTGRESQL_LISTEN="0.0.0.0:5432"
|
||||
export PATRONI_POSTGRESQL_DATA_DIR="data/${PATRONI_SCOPE}"
|
||||
export PATRONI_POSTGRESQL_DATA_DIR="${PATRONI_POSTGRESQL_DATA_DIR:-$PGDATA}"
|
||||
export PATRONI_REPLICATION_USERNAME="${PATRONI_REPLICATION_USERNAME:-replicator}"
|
||||
export PATRONI_REPLICATION_PASSWORD="${PATRONI_REPLICATION_PASSWORD:-abcd}"
|
||||
export PATRONI_REPLICATION_PASSWORD="${PATRONI_REPLICATION_PASSWORD:-replicate}"
|
||||
export PATRONI_SUPERUSER_USERNAME="${PATRONI_SUPERUSER_USERNAME:-postgres}"
|
||||
export PATRONI_SUPERUSER_PASSWORD="${PATRONI_SUPERUSER_PASSWORD:-postgres}"
|
||||
export PATRONI_POSTGRESQL_PGPASS="$HOME/.pgpass"
|
||||
|
||||
cat > /patroni.yml <<__EOF__
|
||||
bootstrap:
|
||||
dcs:
|
||||
postgresql:
|
||||
use_pg_rewind: true
|
||||
|
||||
pg_hba:
|
||||
- host all all 0.0.0.0/0 md5
|
||||
- host replication replicator ${DOCKER_IP}/16 md5
|
||||
__EOF__
|
||||
|
||||
mkdir -p "$HOME/.config/patroni"
|
||||
[ -h "$HOME/.config/patroni/patronictl.yaml" ] || ln -s /patroni.yml "$HOME/.config/patroni/patronictl.yaml"
|
||||
|
||||
[ -z $CHEAT ] && exec python /patroni.py /patroni.yml
|
||||
|
||||
while true; do
|
||||
sleep 60
|
||||
done
|
||||
exec python3 /patroni.py postgres0.yml
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
ETCD_LISTEN_PEER_URLS=http://0.0.0.0:2380
|
||||
ETCD_LISTEN_CLIENT_URLS=http://0.0.0.0:2379
|
||||
ETCD_INITIAL_CLUSTER=etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380
|
||||
ETCD_INITIAL_CLUSTER_STATE=new
|
||||
ETCD_INITIAL_CLUSTER_TOKEN=tutorial
|
||||
@@ -1,3 +1,6 @@
|
||||
PATRONI_SCOPE=demo
|
||||
PATRONI_ETCD_HOSTS='etcd1:2379','etcd2:2379','etcd3:2379'
|
||||
|
||||
PATRONI_RESTAPI_USERNAME=admin
|
||||
PATRONI_RESTAPI_PASSWORD=admin
|
||||
PATRONI_SUPERUSER_USERNAME=postgres
|
||||
@@ -6,3 +9,6 @@ PATRONI_REPLICATION_USERNAME=replicator
|
||||
PATRONI_REPLICATION_PASSWORD=replicate
|
||||
PATRONI_admin_PASSWORD=admin
|
||||
PATRONI_admin_OPTIONS=createdb,createrole
|
||||
|
||||
# for etcdctl
|
||||
ETCDCTL_ENDPOINTS=http://etcd1:2379,http://etcd2:2379,http://etcd3:2379
|
||||
@@ -5,6 +5,11 @@ Contributing guidelines
|
||||
|
||||
Wanna contribute to Patroni? Yay - here is how!
|
||||
|
||||
Chatting
|
||||
--------
|
||||
|
||||
Just want to chat with other Patroni users? Looking for interactive troubleshooting help? Join us on channel #patroni in the `PostgreSQL Slack <https://postgres-slack.herokuapp.com/>`__.
|
||||
|
||||
Reporting issues
|
||||
----------------
|
||||
|
||||
|
||||
+80
-10
@@ -1,6 +1,5 @@
|
||||
.. _environment:
|
||||
|
||||
==================================
|
||||
Environment Configuration Settings
|
||||
==================================
|
||||
|
||||
@@ -13,6 +12,18 @@ Global/Universal
|
||||
- **PATRONI\_NAMESPACE**: path within the configuration store where Patroni will keep information about the cluster. Default value: "/service"
|
||||
- **PATRONI\_SCOPE**: cluster name
|
||||
|
||||
Log
|
||||
---
|
||||
- **PATRONI\_LOG\_LEVEL**: sets the general logging level. Default value is **INFO** (see `the docs for Python logging <https://docs.python.org/3.6/library/logging.html#levels>`_)
|
||||
- **PATRONI\_LOG\_TRACEBACK\_LEVEL**: sets the level where tracebacks will be visible. Default value is **ERROR**. Set it to **DEBUG** if you want to see tracebacks only if you enable **PATRONI\_LOG\_LEVEL=DEBUG**.
|
||||
- **PATRONI\_LOG\_FORMAT**: sets the log formatting string. Default value is **%(asctime)s %(levelname)s: %(message)s** (see `the LogRecord attributes <https://docs.python.org/3.6/library/logging.html#logrecord-attributes>`_)
|
||||
- **PATRONI\_LOG\_DATEFORMAT**: sets the datetime formatting string. (see the `formatTime() documentation <https://docs.python.org/3.6/library/logging.html#logging.Formatter.formatTime>`_)
|
||||
- **PATRONI\_LOG\_MAX\_QUEUE\_SIZE**: Patroni is using two-step logging. Log records are written into the in-memory queue and there is a separate thread which pulls them from the queue and writes to stderr or file. The maximum size of the internal queue is limited by default by **1000** records, which is enough to keep logs for the past 1h20m.
|
||||
- **PATRONI\_LOG\_DIR**: Directory to write application logs to. The directory must exist and be writable by the user executing Patroni. If you set this env variable, the application will retain 4 25MB logs by default. You can tune those retention values with `PATRONI_LOG_FILE_NUM` and `PATRONI_LOG_FILE_SIZE` (see below).
|
||||
- **PATRONI\_LOG\_FILE\_NUM**: The number of application logs to retain.
|
||||
- **PATRONI\_LOG\_FILE\_SIZE**: Size of patroni.log file (in bytes) that triggers a log rolling.
|
||||
- **PATRONI\_LOG\_LOGGERS**: Redefine logging level per python module. Example ``PATRONI_LOG_LOGGERS="{patroni.postmaster: WARNING, urllib3: DEBUG}"``
|
||||
|
||||
Bootstrap configuration
|
||||
-----------------------
|
||||
It is possible to create new database users right after the successful initialization of a new cluster. This process is defined by the following variables:
|
||||
@@ -24,44 +35,103 @@ Example: defining ``PATRONI_admin_PASSWORD=strongpasswd`` and ``PATRONI_admin_OP
|
||||
|
||||
Consul
|
||||
------
|
||||
- **PATRONI\_CONSUL\_HOST**: the host:port for the Consul endpoint.
|
||||
- **PATRONI\_CONSUL\_HOST**: the host:port for the Consul local agent.
|
||||
- **PATRONI\_CONSUL\_URL**: url for the Consul local agent, in format: http(s)://host:port
|
||||
- **PATRONI\_CONSUL\_PORT**: (optional) Consul port
|
||||
- **PATRONI\_CONSUL\_SCHEME**: (optional) **http** or **https**, defaults to **http**
|
||||
- **PATRONI\_CONSUL\_TOKEN**: (optional) ACL token
|
||||
- **PATRONI\_CONSUL\_VERIFY**: (optional) whether to verify the SSL certificate for HTTPS requests
|
||||
- **PATRONI\_CONSUL\_CACERT**: (optional) The ca certificate. If present it will enable validation.
|
||||
- **PATRONI\_CONSUL\_CERT**: (optional) File with the client certificate
|
||||
- **PATRONI\_CONSUL\_KEY**: (optional) File with the client key. Can be empty if the key is part of certificate.
|
||||
- **PATRONI\_CONSUL\_DC**: (optional) Datacenter to communicate with. By default the datacenter of the host is used.
|
||||
- **PATRONI\_CONSUL\_CONSISTENCY**: (optional) Select consul consistency mode. Possible values are ``default``, ``consistent``, or ``stale`` (more details in `consul API reference <https://www.consul.io/api/features/consistency.html/>`__)
|
||||
- **PATRONI\_CONSUL\_CHECKS**: (optional) list of Consul health checks used for the session. By default an empty list is used.
|
||||
- **PATRONI\_CONSUL\_REGISTER\_SERVICE**: (optional) whether or not to register a service with the name defined by the scope parameter and the tag master, replica or standby-leader depending on the node's role. Defaults to **false**
|
||||
- **PATRONI\_CONSUL\_SERVICE\_CHECK\_INTERVAL**: (optional) how often to perform health check against registered url
|
||||
|
||||
Etcd
|
||||
----
|
||||
- **PATRONI\_ETCD\_HOST**: the host:port for the etcd endpoint.
|
||||
- **PATRONI\_ETCD\_URL**: url for the etcd, in format: http(s)://(username:password@)host:port
|
||||
|
||||
- **PATRONI\_ETCD\_PROXY**: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of **PATRONI\_ETCD\_URL**
|
||||
- **PATRONI\_ETCD\_URL**: url for the etcd, in format: http(s)://(username:password@)host:port
|
||||
- **PATRONI\_ETCD\_HOSTS**: list of etcd endpoints in format 'host1:port1','host2:port2',etc...
|
||||
- **PATRONI\_ETCD\_USE\_PROXIES**: If this parameter is set to true, Patroni will consider **hosts** as a list of proxies and will not perform a topology discovery of etcd cluster but stick to a fixed list of **hosts**.
|
||||
- **PATRONI\_ETCD\_PROTOCOL**: http or https, if not specified http is used. If the **url** or **proxy** is specified - will take protocol from them.
|
||||
- **PATRONI\_ETCD\_HOST**: the host:port for the etcd endpoint.
|
||||
- **PATRONI\_ETCD\_SRV**: Domain to search the SRV record(s) for cluster autodiscovery.
|
||||
- **PATRONI\_ETCD\_CACERT**: The ca certificate. If pressent it will enable validation.
|
||||
- **PATRONI\_ETCD\_CERT**: File with the client certificate
|
||||
- **PATRONI\_ETCD\_USERNAME**: username for etcd authentication.
|
||||
- **PATRONI\_ETCD\_PASSWORD**: password for etcd authentication.
|
||||
- **PATRONI\_ETCD\_CACERT**: The ca certificate. If present it will enable validation.
|
||||
- **PATRONI\_ETCD\_CERT**: File with the client certificate.
|
||||
- **PATRONI\_ETCD\_KEY**: File with the client key. Can be empty if the key is part of certificate.
|
||||
|
||||
ZooKeeper
|
||||
---------
|
||||
- **PATRONI\_ZOOKEEPER\_HOSTS**: comma separated list of ZooKeeper cluster members: "'host1:port1','host2:port2','etc...'". It is important to quote every single entity!
|
||||
|
||||
Exhibitor
|
||||
---------
|
||||
- **PATRONI\_EXHIBITOR\_HOSTS**: initial list of Exhibitor (ZooKeeper) nodes in format: 'host1,host2,etc...'. This list updates automatically whenever the Exhibitor (ZooKeeper) cluster topology changes.
|
||||
- **PATRONI\_EXHIBITOR\_PORT**: Exhibitor port.
|
||||
|
||||
.. _kubernetes_environment:
|
||||
|
||||
Kubernetes
|
||||
----------
|
||||
- **PATRONI\_KUBERNETES\_NAMESPACE**: (optional) Kubernetes namespace where the Patroni pod is running. Default value is `default`.
|
||||
- **PATRONI\_KUBERNETES\_LABELS**: Labels in format ``{label1: value1, label2: value2}``. These labels will be used to find existing objects (Pods and either Endpoints or ConfigMaps) associated with the current cluster. Also Patroni will set them on every object (Endpoint or ConfigMap) it creates.
|
||||
- **PATRONI\_KUBERNETES\_SCOPE\_LABEL**: (optional) name of the label containing cluster name. Default value is `cluster-name`.
|
||||
- **PATRONI\_KUBERNETES\_ROLE\_LABEL**: (optional) name of the label containing Postgres role (`master` or `replica`). Patroni will set this label on the pod it is running in. Default value is `role`.
|
||||
- **PATRONI\_KUBERNETES\_USE\_ENDPOINTS**: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state.
|
||||
- **PATRONI\_KUBERNETES\_POD\_IP**: (optional) IP address of the pod Patroni is running in. This value is required when `PATRONI_KUBERNETES_USE_ENDPOINTS` is enabled and is used to populate the leader endpoint subsets when the pod's PostgreSQL is promoted.
|
||||
- **PATRONI\_KUBERNETES\_PORTS**: (optional) if the Service object has the name for the port, the same name must appear in the Endpoint object, otherwise service won't work. For example, if your service is defined as ``{Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}``, then you have to set ``PATRONI_KUBERNETES_PORTS='[{"name": "postgresql", "port": 5432}]'`` and Patroni will use it for updating subsets of the leader Endpoint. This parameter is used only if `PATRONI_KUBERNETES_USE_ENDPOINTS` is set.
|
||||
|
||||
PostgreSQL
|
||||
----------
|
||||
- **PATRONI\_POSTGRESQL\_LISTEN**: IP address + port that Postgres listens to. Multiple comma-separated addresses are permitted, as long as the port component is appended after to the last one with a colon, i.e. ``listen: 127.0.0.1,127.0.0.2:5432``. Patroni will use the first address from this list to establish local connections to the PostgreSQL node.
|
||||
- **PATRONI\_POSTGRESQL\_CONNECT\_ADDRESS**: IP address + port through which Postgres is accessible from other nodes and applications.
|
||||
- **PATRONI\_POSTGRESQL\_DATA\_DIR**: The location of the Postgres data directory, either existing or to be initialized by Patroni.
|
||||
- **PATRONI\_POSTGRESQL\_CONFIG\_DIR**: The location of the Postgres configuration directory, defaults to the data directory. Must be writable by Patroni.
|
||||
- **PATRONI\_POSTGRESQL\_BIN_DIR**: Path to PostgreSQL binaries. (pg_ctl, pg_rewind, pg_basebackup, postgres) The default value is an empty string meaning that PATH environment variable will be used to find the executables.
|
||||
- **PATRONI\_POSTGRESQL\_PGPASS**: path to the `.pgpass <https://www.postgresql.org/docs/current/static/libpq-pgpass.html>`__ password file. Patroni creates this file before executing pg\_basebackup and under some other circumstances. The location must be writable by Patroni.
|
||||
- **PATRONI\_REPLICATION\_USERNAME**: replication username; the user will be created during initialization. Replicas will use this user to access master via streaming replication
|
||||
- **PATRONI\_REPLICATION\_PASSWORD**: replication password; the user will be created during initialization.
|
||||
- **PATRONI\_REPLICATION\_SSLMODE**: (optional) maps to the `sslmode <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE>`__ connection parameter, which allows a client to specify the type of TLS negotiation mode with the server. For more information on how each mode works, please visit the `PostgreSQL documentation <https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS>`__. The default mode is ``prefer``.
|
||||
- **PATRONI\_REPLICATION\_SSLKEY**: (optional) maps to the `sslkey <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY>`__ connection parameter, which specifies the location of the secret key used with the client's certificate.
|
||||
- **PATRONI\_REPLICATION\_SSLCERT**: (optional) maps to the `sslcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT>`__ connection parameter, which specifies the location of the client certificate.
|
||||
- **PATRONI\_REPLICATION\_SSLROOTCERT**: (optional) maps to the `sslrootcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT>`__ connection parameter, which specifies the location of a file containing one ore more certificate authorities (CA) certificates that the client will use to verify a server's certificate.
|
||||
- **PATRONI\_REPLICATION\_SSLCRL**: (optional) maps to the `sslcrl <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCRL>`__ connection parameter, which specifies the location of a file containing a certificate revocation list. A client will reject connecting to any server that has a certificate present in this list.
|
||||
- **PATRONI\_SUPERUSER\_USERNAME**: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres. Also this user is used by pg_rewind.
|
||||
- **PATRONI\_SUPERUSER\_PASSWORD**: password for the superuser, set during initialization (initdb).
|
||||
- **PATRONI\_SUPERUSER\_SSLMODE**: (optional) maps to the `sslmode <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE>`__ connection parameter, which allows a client to specify the type of TLS negotiation mode with the server. For more information on how each mode works, please visit the `PostgreSQL documentation <https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS>`__. The default mode is ``prefer``.
|
||||
- **PATRONI\_SUPERUSER\_SSLKEY**: (optional) maps to the `sslkey <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY>`__ connection parameter, which specifies the location of the secret key used with the client's certificate.
|
||||
- **PATRONI\_SUPERUSER\_SSLCERT**: (optional) maps to the `sslcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT>`__ connection parameter, which specifies the location of the client certificate.
|
||||
- **PATRONI\_SUPERUSER\_SSLROOTCERT**: (optional) maps to the `sslrootcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT>`__ connection parameter, which specifies the location of a file containing one ore more certificate authorities (CA) certificates that the client will use to verify a server's certificate.
|
||||
- **PATRONI\_SUPERUSER\_SSLCRL**: (optional) maps to the `sslcrl <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCRL>`__ connection parameter, which specifies the location of a file containing a certificate revocation list. A client will reject connecting to any server that has a certificate present in this list.
|
||||
- **PATRONI\_REWIND\_USERNAME**: name for the user for ``pg_rewind``; the user will be created during initialization of postgres 11+ and all necessary `permissions <https://www.postgresql.org/docs/11/app-pgrewind.html#id-1.9.5.8.8>`__ will be granted.
|
||||
- **PATRONI\_REWIND\_PASSWORD**: password for the user for ``pg_rewind``; the user will be created during initialization.
|
||||
- **PATRONI\_REWIND\_SSLMODE**: (optional) maps to the `sslmode <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE>`__ connection parameter, which allows a client to specify the type of TLS negotiation mode with the server. For more information on how each mode works, please visit the `PostgreSQL documentation <https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS>`__. The default mode is ``prefer``.
|
||||
- **PATRONI\_REWIND\_SSLKEY**: (optional) maps to the `sslkey <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY>`__ connection parameter, which specifies the location of the secret key used with the client's certificate.
|
||||
- **PATRONI\_REWIND\_SSLCERT**: (optional) maps to the `sslcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT>`__ connection parameter, which specifies the location of the client certificate.
|
||||
- **PATRONI\_REWIND\_SSLROOTCERT**: (optional) maps to the `sslrootcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT>`__ connection parameter, which specifies the location of a file containing one ore more certificate authorities (CA) certificates that the client will use to verify a server's certificate.
|
||||
- **PATRONI\_REWIND\_SSLCRL**: (optional) maps to the `sslcrl <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCRL>`__ connection parameter, which specifies the location of a file containing a certificate revocation list. A client will reject connecting to any server that has a certificate present in this list.
|
||||
|
||||
REST API
|
||||
--------
|
||||
--------
|
||||
- **PATRONI\_RESTAPI\_CONNECT\_ADDRESS**: IP address and port to access the REST API.
|
||||
- **PATRONI\_RESTAPI\_LISTEN**: IP address and port that Patroni will listen to, to provide health-check information for HAProxy.
|
||||
- **PATRONI\_RESTAPI\_USERNAME**: Basic-auth username to protect unsafe REST API endpoints.
|
||||
- **PATRONI\_RESTAPI\_PASSWORD**: Basic-auth password to protect unsafe REST API endpoints.
|
||||
- **PATRONI\_RESTAPI\_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.
|
||||
- **PATRONI\_RESTAPI\_KEYFILE**: Specifies the file with the secret key in the PEM format.
|
||||
- **PATRONI\_RESTAPI\_CAFILE**: Specifies the file with the CA_BUNDLE with certificates of trusted CAs to use while verifying client certs.
|
||||
- **PATRONI\_RESTAPI\_VERIFY\_CLIENT**: ``none`` (default), ``optional`` or ``required``. When ``none`` REST API will not check client certificates. When ``required`` client certificates are required for all REST API calls. When ``optional`` client certificates are required for all unsafe REST API endpoints. When ``required`` is used, then client authentication succeeds, if the certificate signature verification succeeds. For ``optional`` the client cert will only be checked for ``PUT``, ``POST``, ``PATCH``, and ``DELETE`` requests.
|
||||
|
||||
ZooKeeper
|
||||
---------
|
||||
- **PATRONI\_ZOOKEEPER\_HOSTS**: comma separated list of ZooKeeper cluster members: "'host1:port1','host2:port2','etc...'". It is important to quote every single entity!
|
||||
CTL
|
||||
---
|
||||
- **PATRONICTL\_CONFIG\_FILE**: location of the configuration file.
|
||||
- **PATRONI\_CTL\_INSECURE**: Allow connections to REST API without verifying SSL certs.
|
||||
- **PATRONI\_CTL\_CACERT**: Specifies the file with the CA_BUNDLE file or directory with certificates of trusted CAs to use while verifying REST API SSL certs. If not provided patronictl will use the value provided for REST API "cafile" parameter.
|
||||
- **PATRONI\_CTL\_CERTFILE**: Specifies the file with the client certificate in the PEM format. If not provided patronictl will use the value provided for REST API "certfile" parameter.
|
||||
- **PATRONI\_CTL\_KEYFILE**: Specifies the file with the client secret key in the PEM format. If not provided patronictl will use the value provided for REST API "keyfile" parameter.
|
||||
|
||||
+87
-21
@@ -1,8 +1,8 @@
|
||||
.. _readme:
|
||||
|
||||
=================
|
||||
How Patroni Works
|
||||
=================
|
||||
============
|
||||
Introduction
|
||||
============
|
||||
|
||||
Patroni originated as a fork of `Governor <https://github.com/compose/governor>`__, the project from Compose. It includes plenty of new features.
|
||||
|
||||
@@ -13,35 +13,101 @@ For additional background info, see:
|
||||
* `PostgreSQL HA with Kubernetes and Patroni <https://www.youtube.com/watch?v=iruaCgeG7qs>`__, talk by Josh Berkus at KubeCon 2016 (video)
|
||||
* `Feb. 2016 Zalando Tech blog post <https://tech.zalando.de/blog/zalandos-patroni-a-template-for-high-availability-postgresql/>`__
|
||||
|
||||
==================
|
||||
|
||||
Development Status
|
||||
==================
|
||||
------------------
|
||||
|
||||
Patroni is in active development and accepts contributions. See our :ref:`Contributing <contributing>` section below for more details.
|
||||
|
||||
We report new releases information :ref:`here <releases>`.
|
||||
|
||||
===================================
|
||||
Technical Requirements/Installation
|
||||
===================================
|
||||
|
||||
**For Mac**
|
||||
Technical Requirements/Installation
|
||||
-----------------------------------
|
||||
|
||||
**Pre-requirements for Mac OS**
|
||||
|
||||
To install requirements on a Mac, run the following:
|
||||
|
||||
::
|
||||
|
||||
brew install postgresql etcd haproxy libyaml python
|
||||
pip install psycopg2 pyyaml
|
||||
|
||||
=======================
|
||||
.. _psycopg2_install_options:
|
||||
|
||||
**Psycopg2**
|
||||
|
||||
Starting from `psycopg2-2.8 <http://initd.org/psycopg/articles/2019/04/04/psycopg-28-released/>`__ the binary version of psycopg2 will no longer be installed by default. Installing it from the source code requires C compiler and postgres+python dev packages.
|
||||
Since in the python world it is not possible to specify dependency as ``psycopg2 OR psycopg2-binary`` you will have to decide how to install it.
|
||||
|
||||
There are a few options available:
|
||||
|
||||
1. Use the package manager from your distro
|
||||
|
||||
::
|
||||
|
||||
sudo apt-get install python-psycopg2 # install python2 psycopg2 module on Debian/Ubuntu
|
||||
sudo apt-get install python3-psycopg2 # install python3 psycopg2 module on Debian/Ubuntu
|
||||
sudo yum install python-psycopg2 # install python2 psycopg2 on RedHat/Fedora/CentOS
|
||||
|
||||
2. Install psycopg2 from the binary package
|
||||
|
||||
::
|
||||
|
||||
pip install psycopg2-binary
|
||||
|
||||
3. Install psycopg2 from source
|
||||
|
||||
::
|
||||
|
||||
pip install psycopg2>=2.5.4
|
||||
|
||||
**General installation for pip**
|
||||
|
||||
Patroni can be installed with pip:
|
||||
|
||||
::
|
||||
|
||||
pip install patroni[dependencies]
|
||||
|
||||
where dependencies can be either empty, or consist of one or more of the following:
|
||||
|
||||
etcd
|
||||
`python-etcd` module in order to use Etcd as DCS
|
||||
consul
|
||||
`python-consul` module in order to use Consul as DCS
|
||||
zookeeper
|
||||
`kazoo` module in order to use Zookeeper as DCS
|
||||
exhibitor
|
||||
`kazoo` module in order to use Exhibitor as DCS (same dependencies as for Zookeeper)
|
||||
kubernetes
|
||||
`kubernetes` module in order to use Kubernetes as DCS in Patroni
|
||||
aws
|
||||
`boto` in order to use AWS callbacks
|
||||
|
||||
For example, the command in order to install Patroni together with dependencies for Etcd as a DCS and AWS callbacks is:
|
||||
|
||||
::
|
||||
|
||||
pip install patroni[etcd,aws]
|
||||
|
||||
Note that external tools to call in the replica creation or custom bootstrap scripts (i.e. WAL-E) should be installed
|
||||
independently of Patroni.
|
||||
|
||||
|
||||
.. _running_configuring:
|
||||
|
||||
Running and Configuring
|
||||
=======================
|
||||
-----------------------
|
||||
|
||||
The following section assumes Patroni repository as being cloned from https://github.com/zalando/patroni. Namely, you
|
||||
will need example configuration files `postgres0.yml` and `postgres1.yml`. If you installed Patroni with pip, you can
|
||||
obtain those files from the git repository and replace `./patroni.py` below with `patroni` command.
|
||||
|
||||
To get started, do the following from different terminals:
|
||||
::
|
||||
|
||||
> etcd --data-dir=data/etcd
|
||||
> etcd --data-dir=data/etcd --enable-v2=true
|
||||
> ./patroni.py postgres0.yml
|
||||
> ./patroni.py postgres1.yml
|
||||
|
||||
@@ -60,27 +126,27 @@ run:
|
||||
|
||||
> psql --host 127.0.0.1 --port 5000 postgres
|
||||
|
||||
==================
|
||||
|
||||
YAML Configuration
|
||||
==================
|
||||
------------------
|
||||
|
||||
Go :ref:`here <settings>` for comprehensive information about settings for etcd, consul, and ZooKeeper. And for an example, see `postgres0.yml <https://github.com/zalando/patroni/blob/master/postgres0.yml>`__.
|
||||
|
||||
=========================
|
||||
|
||||
Environment Configuration
|
||||
=========================
|
||||
-------------------------
|
||||
|
||||
Go :ref:`here <environment>` for comprehensive information about configuring(overriding) settings via environment variables.
|
||||
|
||||
===================
|
||||
|
||||
Replication Choices
|
||||
===================
|
||||
-------------------
|
||||
|
||||
Patroni uses Postgres' streaming replication, which is asynchronous by default. Patroni's asynchronous replication configuration allows for ``maximum_lag_on_failover`` settings. This setting ensures failover will not occur if a follower is more than a certain number of bytes behind the leader. This setting should be increased or decreased based on business requirements. It's also possible to use synchronous replication for better durability guarantees. See :ref:`replication modes documentation <replication_modes>` for details.
|
||||
|
||||
======================================
|
||||
|
||||
Applications Should Not Use Superusers
|
||||
======================================
|
||||
--------------------------------------
|
||||
|
||||
When connecting from an application, always use a non-superuser. Patroni requires access to the database to function properly. By using a superuser from an application, you can potentially use the entire connection pool, including the connections reserved for superusers, with the ``superuser_reserved_connections`` setting. If Patroni cannot access the Primary because the connection pool is full, behavior will be undesirable.
|
||||
|
||||
|
||||
+204
-69
@@ -4,107 +4,242 @@
|
||||
YAML Configuration Settings
|
||||
===========================
|
||||
|
||||
.. _dynamic_configuration_settings:
|
||||
|
||||
Dynamic configuration settings
|
||||
------------------------------
|
||||
|
||||
Dynamic configuration is stored in the DCS (Distributed Configuration Store) and applied on all cluster nodes. Some parameters, like **loop_wait**, **ttl**, **postgresql.parameters.max_connections**, **postgresql.parameters.max_worker_processes** and so on could be set only in the dynamic configuration. Some other parameters like **postgresql.listen**, **postgresql.data_dir** could be set only locally, i.e. in the Patroni config file or via :ref:`configuration <environment>` variable. In most cases the local configuration will override the dynamic configuration. In order to change the dynamic configuration you can use either ``patronictl edit-config`` tool or Patroni :ref:`REST API <rest_api>`.
|
||||
|
||||
- **loop\_wait**: the number of seconds the loop will sleep. Default value: 10
|
||||
- **ttl**: the TTL to acquire the leader lock (in seconds). Think of it as the length of time before initiation of the automatic failover process. Default value: 30
|
||||
- **retry\_timeout**: timeout for DCS and PostgreSQL operation retries (in seconds). DCS or network issues shorter than this will not cause Patroni to demote the leader. Default value: 10
|
||||
- **maximum\_lag\_on\_failover**: the maximum bytes a follower may lag to be able to participate in leader election.
|
||||
- **max\_timelines\_history**: maximum number of timeline history items kept in DCS. Default value: 0. When set to 0, it keeps the full history in DCS.
|
||||
- **master\_start\_timeout**: the amount of time a master is allowed to recover from failures before failover is triggered (in seconds). Default is 300 seconds. When set to 0 failover is done immediately after a crash is detected if possible. When using asynchronous replication a failover can cause lost transactions. Worst case failover time for master failure is: loop\_wait + master\_start\_timeout + loop\_wait, unless master\_start\_timeout is zero, in which case it's just loop\_wait. Set the value according to your durability/availability tradeoff.
|
||||
- **master\_stop\_timeout**: The number of seconds Patroni is allowed to wait when stopping Postgres and effective only when synchronous_mode is enabled. When set to > 0 and the synchronous_mode is enabled, Patroni sends SIGKILL to the postmaster if the stop operation is running for more than the value set by master_stop_timeout. Set the value according to your durability/availability tradeoff. If the parameter is not set or set <= 0, master_stop_timeout does not apply.
|
||||
- **synchronous\_mode**: turns on synchronous replication mode. In this mode a replica will be chosen as synchronous and only the latest leader and synchronous replica are able to participate in leader election. Synchronous mode makes sure that successfully committed transactions will not be lost at failover, at the cost of losing availability for writes when Patroni cannot ensure transaction durability. See :ref:`replication modes documentation <replication_modes>` for details.
|
||||
- **synchronous\_mode\_strict**: prevents disabling synchronous replication if no synchronous replicas are available, blocking all client writes to the master. See :ref:`replication modes documentation <replication_modes>` for details.
|
||||
- **postgresql**:
|
||||
- **use\_pg\_rewind**: whether or not to use pg_rewind. Defaults to `false`.
|
||||
- **use\_slots**: whether or not to use replication slots. Defaults to `true` on PostgreSQL 9.4+.
|
||||
- **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower. There is no recovery.conf anymore in PostgreSQL 12, but you may continue using this section, because Patroni handles it transparently.
|
||||
- **parameters**: list of configuration settings for Postgres.
|
||||
- **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
|
||||
- **slots**: define permanent replication slots. These slots will be preserved during switchover/failover. Patroni will try to create slots before opening connections to the cluster.
|
||||
- **my_slot_name**: the name of replication slot. If the permanent slot name matches with the name of the current primary it will not be created. Everything else is the responsibility of the operator to make sure that there are no clashes in names between replication slots automatically created by Patroni for members and permanent replication slots.
|
||||
- **type**: slot type. Could be ``physical`` or ``logical``. If the slot is logical, you have to additionally define ``database`` and ``plugin``.
|
||||
- **database**: the database name where logical slots should be created.
|
||||
- **plugin**: the plugin name for the logical slot.
|
||||
|
||||
Global/Universal
|
||||
----------------
|
||||
- **name**: the name of the host. Must be unique for the cluster.
|
||||
- **namespace**: path within the configuration store where Patroni will keep information about the cluster. Default value: "/service"
|
||||
- **scope**: cluster name
|
||||
|
||||
Log
|
||||
---
|
||||
- **level**: sets the general logging level. Default value is **INFO** (see `the docs for Python logging <https://docs.python.org/3.6/library/logging.html#levels>`_)
|
||||
- **traceback\_level**: sets the level where tracebacks will be visible. Default value is **ERROR**. Set it to **DEBUG** if you want to see tracebacks only if you enable **log.level=DEBUG**.
|
||||
- **format**: sets the log formatting string. Default value is **%(asctime)s %(levelname)s: %(message)s** (see `the LogRecord attributes <https://docs.python.org/3.6/library/logging.html#logrecord-attributes>`_)
|
||||
- **dateformat**: sets the datetime formatting string. (see the `formatTime() documentation <https://docs.python.org/3.6/library/logging.html#logging.Formatter.formatTime>`_)
|
||||
- **max\_queue\_size**: Patroni is using two-step logging. Log records are written into the in-memory queue and there is a separate thread which pulls them from the queue and writes to stderr or file. The maximum size of the internal queue is limited by default by **1000** records, which is enough to keep logs for the past 1h20m.
|
||||
- **dir**: Directory to write application logs to. The directory must exist and be writable by the user executing Patroni. If you set this value, the application will retain 4 25MB logs by default. You can tune those retention values with `file_num` and `file_size` (see below).
|
||||
- **file\_num**: The number of application logs to retain.
|
||||
- **file\_size**: Size of patroni.log file (in bytes) that triggers a log rolling.
|
||||
- **loggers**: This section allows redefining logging level per python module
|
||||
- **patroni.postmaster: WARNING**
|
||||
- **urllib3: DEBUG**
|
||||
|
||||
.. _bootstrap_settings:
|
||||
|
||||
Bootstrap configuration
|
||||
-----------------------
|
||||
- **dcs**: This section will be written into `/<namespace>/<scope>/config` of a given configuration store after initializing of new cluster. This is the global configuration for the cluster. If you want to change some parameters for all cluster nodes - just do it in DCS (or via Patroni API) and all nodes will apply this configuration.
|
||||
- **loop\_wait**: the number of seconds the loop will sleep. Default value: 10
|
||||
- **ttl**: the TTL to acquire the leader lock. Think of it as the length of time before initiation of the automatic failover process. Default value: 30
|
||||
- **maximum\_lag\_on\_failover**: the maximum bytes a follower may lag to be able to participate in leader election.
|
||||
- **master\_start\_timeout**: the amount of time a master is allowed to recover from failures before failover is triggered. Default is 300 seconds. When set to 0 failover is done immediately after a crash is detected if possible. When using asynchronous replication a failover can cause lost transactions. Best worst case failover time for master failure is: loop\_wait + master\_start\_timeout + loop\_wait, unless master\_start\_timeout is zero, in which case it's just loop\_wait. Set the value according to your durability/availability tradeoff.
|
||||
- **synchronous\_mode**: turns on synchronous replication mode. In this mode a replica will be chosen as synchronous and only the latest leader and synchronous replica are able to participate in leader election. Synchronous mode makes sure that succesfully committed transactions will not be lost at failover, at the cost of losing availability for writes when Patroni cannot ensure transaction durability. See `replication modes documentation <https://github.com/zalando/patroni/blob/master/docs/replication_modes.rst>`__ for details.
|
||||
- **postgresql**:
|
||||
- **use\_pg\_rewind**:whether or not to use pg_rewind
|
||||
- **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.
|
||||
- **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work.
|
||||
- **initdb**: List options to be passed on to initdb.
|
||||
- **- data-checksums**: Must be enabled when pg_rewind is needed on 9.3.
|
||||
- **- encoding: UTF8**: default encoding for new databases.
|
||||
- **- locale: UTF8**: default locale for new databases.
|
||||
- **pg\_hba**: list of lines that you should add to pg\_hba.conf.
|
||||
- **- host all all 0.0.0.0/0 md5**.
|
||||
- **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication.
|
||||
- **users**: Some additional users users which needs to be created after initializing new cluster
|
||||
- **admin**: the name of user
|
||||
- **password: zalando**:
|
||||
- **options**: list of options for CREATE USER statement
|
||||
- **- createrole**
|
||||
- **- createdb**
|
||||
- **post_init**: An additional script that will be executed after initializing the cluster. The script receives a connection string URL (with the cluster superuser as a user name). The PGPASSFILE variable is set to the location of pgpass file.
|
||||
- **bootstrap**:
|
||||
- **dcs**: This section will be written into `/<namespace>/<scope>/config` of the given configuration store after initializing of new cluster. The global dynamic configuration for the cluster. Under the ``bootstrap.dcs`` you can put any of the parameters described in the :ref:`Dynamic Configuration settings <dynamic_configuration_settings>` and after Patroni initialized (bootstrapped) the new cluster, it will write this section into `/<namespace>/<scope>/config` of the configuration store. All later changes of ``bootstrap.dcs`` will not take any effect! If you want to change them please use either ``patronictl edit-config`` or Patroni :ref:`REST API <rest_api>`.
|
||||
- **method**: custom script to use for bootstrapping this cluster.
|
||||
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``
|
||||
parameter is present in the configuration file.
|
||||
- **initdb**: List options to be passed on to initdb.
|
||||
- **- data-checksums**: Must be enabled when pg_rewind is needed on 9.3.
|
||||
- **- encoding: UTF8**: default encoding for new databases.
|
||||
- **- locale: UTF8**: default locale for new databases.
|
||||
- **pg\_hba**: list of lines that you should add to pg\_hba.conf.
|
||||
- **- host all all 0.0.0.0/0 md5**.
|
||||
- **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication.
|
||||
- **users**: Some additional users which need to be created after initializing new cluster
|
||||
- **admin**: the name of user
|
||||
- **password: zalando**:
|
||||
- **options**: list of options for CREATE USER statement
|
||||
- **- createrole**
|
||||
- **- createdb**
|
||||
- **post\_bootstrap** or **post\_init**: An additional script that will be executed after initializing the cluster. The script receives a connection string URL (with the cluster superuser as a user name). The PGPASSFILE variable is set to the location of pgpass file.
|
||||
|
||||
.. _consul_settings:
|
||||
|
||||
Consul
|
||||
------
|
||||
- **host**: the host:port for the Consul endpoint.
|
||||
Most of the parameters are optional, but you have to specify one of the **host** or **url**
|
||||
|
||||
- **host**: the host:port for the Consul local agent.
|
||||
- **url**: url for the Consul local agent, in format: http(s)://host:port.
|
||||
- **port**: (optional) Consul port.
|
||||
- **scheme**: (optional) **http** or **https**, defaults to **http**.
|
||||
- **token**: (optional) ACL token.
|
||||
- **verify**: (optional) whether to verify the SSL certificate for HTTPS requests.
|
||||
- **cacert**: (optional) The ca certificate. If present it will enable validation.
|
||||
- **cert**: (optional) file with the client certificate.
|
||||
- **key**: (optional) file with the client key. Can be empty if the key is part of **cert**.
|
||||
- **dc**: (optional) Datacenter to communicate with. By default the datacenter of the host is used.
|
||||
- **consistency**: (optional) Select consul consistency mode. Possible values are ``default``, ``consistent``, or ``stale`` (more details in `consul API reference <https://www.consul.io/api/features/consistency.html/>`__)
|
||||
- **checks**: (optional) list of Consul health checks used for the session. By default an empty list is used.
|
||||
- **register\_service**: (optional) whether or not to register a service with the name defined by the scope parameter and the tag master, replica or standby-leader depending on the node's role. Defaults to **false**.
|
||||
- **service\_check\_interval**: (optional) how often to perform health check against registered url.
|
||||
|
||||
Etcd
|
||||
----
|
||||
Most of the parameters are optional, but you have to specify one of the **host**, **url**, **proxy** or **srv**
|
||||
Most of the parameters are optional, but you have to specify one of the **host**, **hosts**, **url**, **proxy** or **srv**
|
||||
|
||||
- **host**: the host:port for the etcd endpoint.
|
||||
- **url**: url for the etcd
|
||||
- **proxy**: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of **url**
|
||||
- **hosts**: list of etcd endpoint in format host1:port1,host2:port2,etc... Could be a comma separated string or an actual yaml list.
|
||||
- **use\_proxies**: If this parameter is set to true, Patroni will consider **hosts** as a list of proxies and will not perform a topology discovery of etcd cluster.
|
||||
- **url**: url for the etcd.
|
||||
- **proxy**: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of **url**.
|
||||
- **srv**: Domain to search the SRV record(s) for cluster autodiscovery.
|
||||
- **protocol**: (optional) http or https, if not specified http is used. If the **url** or **proxy** is specified - will take protocol from them.
|
||||
- **username**: (optional) username for etcd authentication
|
||||
- **username**: (optional) username for etcd authentication.
|
||||
- **password**: (optional) password for etcd authentication.
|
||||
- **cacert**: (optional) The ca certificate. If pressent it will enable validation.
|
||||
- **cert**: (optional) file with the client certificate
|
||||
- **cacert**: (optional) The ca certificate. If present it will enable validation.
|
||||
- **cert**: (optional) file with the client certificate.
|
||||
- **key**: (optional) file with the client key. Can be empty if the key is part of **cert**.
|
||||
|
||||
ZooKeeper
|
||||
----------
|
||||
- **hosts**: list of ZooKeeper cluster members in format: ['host1:port1', 'host2:port2', 'etc...'].
|
||||
|
||||
Exhibitor
|
||||
---------
|
||||
- **hosts**: initial list of Exhibitor (ZooKeeper) nodes in format: 'host1,host2,etc...'. This list updates automatically whenever the Exhibitor (ZooKeeper) cluster topology changes.
|
||||
- **poll\_interval**: how often the list of ZooKeeper and Exhibitor nodes should be updated from Exhibitor
|
||||
- **poll\_interval**: how often the list of ZooKeeper and Exhibitor nodes should be updated from Exhibitor.
|
||||
- **port**: Exhibitor port.
|
||||
|
||||
.. _kubernetes_settings:
|
||||
|
||||
Kubernetes
|
||||
----------
|
||||
- **namespace**: (optional) Kubernetes namespace where Patroni pod is running. Default value is `default`.
|
||||
- **labels**: Labels in format ``{label1: value1, label2: value2}``. These labels will be used to find existing objects (Pods and either Endpoints or ConfigMaps) associated with the current cluster. Also Patroni will set them on every object (Endpoint or ConfigMap) it creates.
|
||||
- **scope\_label**: (optional) name of the label containing cluster name. Default value is `cluster-name`.
|
||||
- **role\_label**: (optional) name of the label containing role (master or replica). Patroni will set this label on the pod it runs in. Default value is ``role``.
|
||||
- **use\_endpoints**: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state.
|
||||
- **pod\_ip**: (optional) IP address of the pod Patroni is running in. This value is required when `use_endpoints` is enabled and is used to populate the leader endpoint subsets when the pod's PostgreSQL is promoted.
|
||||
- **ports**: (optional) if the Service object has the name for the port, the same name must appear in the Endpoint object, otherwise service won't work. For example, if your service is defined as ``{Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}``, then you have to set ``kubernetes.ports: [{"name": "postgresql", "port": 5432}]`` and Patroni will use it for updating subsets of the leader Endpoint. This parameter is used only if `kubernetes.use_endpoints` is set.
|
||||
|
||||
.. _postgresql_settings:
|
||||
|
||||
PostgreSQL
|
||||
----------
|
||||
- **authentication**:
|
||||
- **superuser**:
|
||||
- **username**: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres.
|
||||
- **password**: password for the superuser, set during initialization (initdb).
|
||||
- **replication**:
|
||||
- **username**: replication username; the user will be created during initialization. Replicas will use this user to access master via streaming replication
|
||||
- **password**: replication password; the user will be created during initialization.
|
||||
- **callbacks**: callback scripts to run on certain actions. Patroni will pass the action, role and cluster name. (See scripts/aws.py as an example of how to write them.)
|
||||
- **on\_reload**: run this script when configuration reload is triggered.
|
||||
- **on\_restart**: run this script when the cluster restarts.
|
||||
- **on\_role\_change**: run this script when the cluster is being promoted or demoted.
|
||||
- **on\_start**: run this script when the cluster starts.
|
||||
- **on\_stop**: run this script when the cluster stops.
|
||||
- **connect\_address**: IP address + port through which Postgres is accessible from other nodes and applications.
|
||||
- **create\_replica\_methods**: an ordered list of the create methods for turning a Patroni node into a new replica. "basebackup" is the default method; other methods are assumed to refer to scripts, each of which is configured as its own config item.
|
||||
- **data\_dir**: The location of the Postgres data directory, either existing or to be initialized by Patroni.
|
||||
- **bin\_dir**: Path to PostgreSQL binaries. (pg_ctl, pg_rewind, pg_basebackup, postgres) The default value is an empty string meaning that PATH environment variable will be used to find the executables.
|
||||
- **listen**: IP address + port that Postgres listens to; must be accessible from other nodes in the cluster, if you're using streaming replication. Multiple comma-separated addresses are permitted, as long as the port component is appended after to the last one with a colon, i.e. ``listen: 127.0.0.1,127.0.0.2:5432``. Patroni will use the first address from this list to establish local connections to the PostgreSQL node.
|
||||
- **pgpass**: path to the `.pgpass <https://www.postgresql.org/docs/current/static/libpq-pgpass.html>`__ password file. Patroni creates this file before executing pg\_basebackup, the post_init script and under some other circumstances. The location must be writable by Patroni.
|
||||
- **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower.
|
||||
- **custom_conf** : path to an optional custom ``postgresql.conf`` file, that will be used in place of ``postgresql.base.conf``. The file must exist on all cluster nodes, be readable by PostgreSQL and will be included from its location on the real ``postgresql.conf``. Note that Patroni will not monitor this file for changes, nor backup it. However, its settings can still be overriden by Patroni's own configuration facilities - see `dynamic configuration <https://github.com/zalando/patroni/blob/master/docs/dynamic_configuration.rst>`__ for details.
|
||||
- **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work.
|
||||
- **pg\_ctl\_timeout**: How long should pg_ctl wait when doing ``start``, ``stop`` or ``restart``. Default value is 60 seconds.
|
||||
- **use\_pg\_rewind**: try to use pg\_rewind on the former leader when it joins cluster as a replica.
|
||||
- **remove\_data\_directory\_on\_rewind\_failure**: If this option is enabled, Patroni will remove postgres data directory and recreate replica. Otherwise it will try to follow the new leader. Default value is **false**.
|
||||
- **replica\_method** for each create_replica_method other than basebackup, you would add a configuration section of the same name. At a minimum, this should include "command" with a full path to the actual script to be executed. Other configuration parameters will be passed along to the script in the form "parameter=value".
|
||||
- **postgresql**:
|
||||
- **authentication**:
|
||||
- **superuser**:
|
||||
- **username**: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres.
|
||||
- **password**: password for the superuser, set during initialization (initdb).
|
||||
- **sslmode**: (optional) maps to the `sslmode <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE>`__ connection parameter, which allows a client to specify the type of TLS negotiation mode with the server. For more information on how each mode works, please visit the `PostgreSQL documentation <https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS>`__. The default mode is ``prefer``.
|
||||
- **sslkey**: (optional) maps to the `sslkey <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY>`__ connection parameter, which specifies the location of the secret key used with the client's certificate.
|
||||
- **sslcert**: (optional) maps to the `sslcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT>`__ connection parameter, which specifies the location of the client certificate.
|
||||
- **sslrootcert**: (optional) maps to the `sslrootcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT>`__ connection parameter, which specifies the location of a file containing one ore more certificate authorities (CA) certificates that the client will use to verify a server's certificate.
|
||||
- **sslcrl**: (optional) maps to the `sslcrl <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCRL>`__ connection parameter, which specifies the location of a file containing a certificate revocation list. A client will reject connecting to any server that has a certificate present in this list.
|
||||
- **replication**:
|
||||
- **username**: replication username; the user will be created during initialization. Replicas will use this user to access master via streaming replication
|
||||
- **password**: replication password; the user will be created during initialization.
|
||||
- **sslmode**: (optional) maps to the `sslmode <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE>`__ connection parameter, which allows a client to specify the type of TLS negotiation mode with the server. For more information on how each mode works, please visit the `PostgreSQL documentation <https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS>`__. The default mode is ``prefer``.
|
||||
- **sslkey**: (optional) maps to the `sslkey <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY>`__ connection parameter, which specifies the location of the secret key used with the client's certificate.
|
||||
- **sslcert**: (optional) maps to the `sslcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT>`__ connection parameter, which specifies the location of the client certificate.
|
||||
- **sslrootcert**: (optional) maps to the `sslrootcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT>`__ connection parameter, which specifies the location of a file containing one ore more certificate authorities (CA) certificates that the client will use to verify a server's certificate.
|
||||
- **sslcrl**: (optional) maps to the `sslcrl <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCRL>`__ connection parameter, which specifies the location of a file containing a certificate revocation list. A client will reject connecting to any server that has a certificate present in this list.
|
||||
- **rewind**:
|
||||
- **username**: name for the user for ``pg_rewind``; the user will be created during initialization of postgres 11+ and all necessary `permissions <https://www.postgresql.org/docs/11/app-pgrewind.html#id-1.9.5.8.8>`__ will be granted.
|
||||
- **password**: password for the user for ``pg_rewind``; the user will be created during initialization.
|
||||
- **sslmode**: (optional) maps to the `sslmode <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLMODE>`__ connection parameter, which allows a client to specify the type of TLS negotiation mode with the server. For more information on how each mode works, please visit the `PostgreSQL documentation <https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS>`__. The default mode is ``prefer``.
|
||||
- **sslkey**: (optional) maps to the `sslkey <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLKEY>`__ connection parameter, which specifies the location of the secret key used with the client's certificate.
|
||||
- **sslcert**: (optional) maps to the `sslcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCERT>`__ connection parameter, which specifies the location of the client certificate.
|
||||
- **sslrootcert**: (optional) maps to the `sslrootcert <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLROOTCERT>`__ connection parameter, which specifies the location of a file containing one ore more certificate authorities (CA) certificates that the client will use to verify a server's certificate.
|
||||
- **sslcrl**: (optional) maps to the `sslcrl <https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLCRL>`__ connection parameter, which specifies the location of a file containing a certificate revocation list. A client will reject connecting to any server that has a certificate present in this list.
|
||||
- **callbacks**: callback scripts to run on certain actions. Patroni will pass the action, role and cluster name. (See scripts/aws.py as an example of how to write them.)
|
||||
- **on\_reload**: run this script when configuration reload is triggered.
|
||||
- **on\_restart**: run this script when the postgres restarts (without changing role).
|
||||
- **on\_role\_change**: run this script when the postgres is being promoted or demoted.
|
||||
- **on\_start**: run this script when the postgres starts.
|
||||
- **on\_stop**: run this script when the postgres stops.
|
||||
- **connect\_address**: IP address + port through which Postgres is accessible from other nodes and applications.
|
||||
- **create\_replica\_methods**: an ordered list of the create methods for turning a Patroni node into a new replica.
|
||||
"basebackup" is the default method; other methods are assumed to refer to scripts, each of which is configured as its
|
||||
own config item. See :ref:`custom replica creation methods documentation <custom_replica_creation>` for further explanation.
|
||||
- **data\_dir**: The location of the Postgres data directory, either :ref:`existing <existing_data>` or to be initialized by Patroni.
|
||||
- **config\_dir**: The location of the Postgres configuration directory, defaults to the data directory. Must be writable by Patroni.
|
||||
- **bin\_dir**: Path to PostgreSQL binaries (pg_ctl, pg_rewind, pg_basebackup, postgres). The default value is an empty string meaning that PATH environment variable will be used to find the executables.
|
||||
- **listen**: IP address + port that Postgres listens to; must be accessible from other nodes in the cluster, if you're using streaming replication. Multiple comma-separated addresses are permitted, as long as the port component is appended after to the last one with a colon, i.e. ``listen: 127.0.0.1,127.0.0.2:5432``. Patroni will use the first address from this list to establish local connections to the PostgreSQL node.
|
||||
- **use\_unix\_socket**: specifies that Patroni should prefer to use unix sockets to connect to the cluster. Default value is ``false``. If ``unix_socket_directories`` is defined, Patroni will use the first suitable value from it to connect to the cluster and fallback to tcp if nothing is suitable. If ``unix_socket_directories`` is not specified in ``postgresql.parameters``, Patroni will assume that the default value should be used and omit ``host`` from the connection parameters.
|
||||
- **pgpass**: path to the `.pgpass <https://www.postgresql.org/docs/current/static/libpq-pgpass.html>`__ password file. Patroni creates this file before executing pg\_basebackup, the post_init script and under some other circumstances. The location must be writable by Patroni.
|
||||
- **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower.
|
||||
- **custom\_conf** : path to an optional custom ``postgresql.conf`` file, that will be used in place of ``postgresql.base.conf``. The file must exist on all cluster nodes, be readable by PostgreSQL and will be included from its location on the real ``postgresql.conf``. Note that Patroni will not monitor this file for changes, nor backup it. However, its settings can still be overridden by Patroni's own configuration facilities - see :ref:`dynamic configuration <dynamic_configuration>` for details.
|
||||
- **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work.
|
||||
- **pg\_hba**: list of lines that Patroni will use to generate ``pg_hba.conf``. This parameter has higher priority than ``bootstrap.pg_hba``. Together with :ref:`dynamic configuration <dynamic_configuration>` it simplifies management of ``pg_hba.conf``.
|
||||
- **- host all all 0.0.0.0/0 md5**.
|
||||
- **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication.
|
||||
- **pg\_ident**: list of lines that Patroni will use to generate ``pg_ident.conf``. Together with :ref:`dynamic configuration <dynamic_configuration>` it simplifies management of ``pg_ident.conf``.
|
||||
- **- mapname1 systemname1 pguser1**.
|
||||
- **- mapname1 systemname2 pguser2**.
|
||||
- **pg\_ctl\_timeout**: How long should pg_ctl wait when doing ``start``, ``stop`` or ``restart``. Default value is 60 seconds.
|
||||
- **use\_pg\_rewind**: try to use pg\_rewind on the former leader when it joins cluster as a replica.
|
||||
- **remove\_data\_directory\_on\_rewind\_failure**: If this option is enabled, Patroni will remove the PostgreSQL data directory and recreate the replica. Otherwise it will try to follow the new leader. Default value is **false**.
|
||||
- **remove\_data\_directory\_on\_diverged\_timelines**: Patroni will remove the PostgreSQL data directory and recreate the replica if it notices that timelines are diverging and the former master can not start streaming from the new master. This option is useful when ``pg_rewind`` can not be used. Default value is **false**.
|
||||
- **replica\_method**: for each create_replica_methods other than basebackup, you would add a configuration section of the same name. At a minimum, this should include "command" with a full path to the actual script to be executed. Other configuration parameters will be passed along to the script in the form "parameter=value".
|
||||
|
||||
REST API
|
||||
--------
|
||||
- **connect\_address**: IP address and port to access the REST API.
|
||||
- **listen**: IP address and port that Patroni will listen to, to provide health-check information for HAProxy.
|
||||
- **Optional**:
|
||||
- **authentication**:
|
||||
--------
|
||||
- **restapi**:
|
||||
- **connect\_address**: IP address (or hostname) and port, to access the Patroni's :ref:`REST API <rest_api>`. All the members of the cluster must be able to connect to this address, so unless the Patroni setup is intended for a demo inside the localhost, this address must be a non "localhost" or loopback address (ie: "localhost" or "127.0.0.1"). It can serve as an endpoint for HTTP health checks (read below about the "listen" REST API parameter), and also for user queries (either directly or via the REST API), as well as for the health checks done by the cluster members during leader elections (for example, to determine whether the master is still running, or if there is a node which has a WAL position that is ahead of the one doing the query; etc.) The connect_address is put in the member key in DCS, making it possible to translate the member name into the address to connect to its REST API.
|
||||
|
||||
- **listen**: IP address (or hostname) and port that Patroni will listen to for the REST API - to provide also the same health checks and cluster messaging between the participating nodes, as described above. to provide health-check information for HAProxy (or any other load balancer capable of doing a HTTP "OPTION" or "GET" checks).
|
||||
|
||||
- **authentication**: (optional)
|
||||
- **username**: Basic-auth username to protect unsafe REST API endpoints.
|
||||
- **password**: Basic-auth password to protect unsafe REST API endpoints.
|
||||
- **certfile**: (optional): 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**: (optional): Specifies the file with the secret key in the PEM format.
|
||||
- **cafile**: (optional): Specifies the file with the CA_BUNDLE with certificates of trusted CAs to use while verifying client certs.
|
||||
- **verify\_client**: (optional): ``none`` (default), ``optional`` or ``required``. When ``none`` REST API will not check client certificates. When ``required`` client certificates are required for all REST API calls. When ``optional`` client certificates are required for all unsafe REST API endpoints. When ``required`` is used, then client authentication succeeds, if the certificate signature verification succeeds. For ``optional`` the client cert will only be checked for ``PUT``, ``POST``, ``PATCH``, and ``DELETE`` requests.
|
||||
|
||||
- **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.
|
||||
.. _patronictl_settings:
|
||||
|
||||
ZooKeeper
|
||||
----------
|
||||
- **hosts**: list of ZooKeeper cluster members in format: ['host1:port1', 'host2:port2', 'etc...'].
|
||||
CTL
|
||||
---
|
||||
- **ctl**: (optional)
|
||||
- **insecure**: Allow connections to REST API without verifying SSL certs.
|
||||
- **cacert**: Specifies the file with the CA_BUNDLE file or directory with certificates of trusted CAs to use while verifying REST API SSL certs. If not provided patronictl will use the value provided for REST API "cafile" parameter.
|
||||
- **certfile**: Specifies the file with the client certificate in the PEM format. If not provided patronictl will use the value provided for REST API "certfile" parameter.
|
||||
- **keyfile**: Specifies the file with the client secret key in the PEM format. If not provided patronictl will use the value provided for REST API "keyfile" parameter.
|
||||
|
||||
Watchdog
|
||||
--------
|
||||
- **mode**: ``off``, ``automatic`` or ``required``. When ``off`` watchdog is disabled. When ``automatic`` watchdog will be used if available, but ignored if it is not. When ``required`` the node will not become a leader unless watchdog can be successfully enabled.
|
||||
- **device**: Path to watchdog device. Defaults to ``/dev/watchdog``.
|
||||
- **safety_margin**: Number of seconds of safety margin between watchdog triggering and leader key expiration.
|
||||
|
||||
Tags
|
||||
----
|
||||
- **nofailover**: ``true`` or ``false``, controls whether this node is allowed to participate in the leader race and become a leader. Defaults to ``false``
|
||||
- **clonefrom**: ``true`` or ``false``. If set to ``true`` other nodes might prefer to use this node for bootstrap (take ``pg_basebackup`` from). If there are several nodes with ``clonefrom`` tag set to ``true`` the node to bootstrap from will be chosen randomly. The default value is ``false``.
|
||||
- **noloadbalance**: ``true`` or ``false``. If set to ``true`` the node will return HTTP Status Code 503 for the ``GET /replica`` REST API health-check and therefore will be excluded from the load-balancing. Defaults to ``false``.
|
||||
- **replicatefrom**: The IP address/hostname of another replica. Used to support cascading replication.
|
||||
- **nosync**: ``true`` or ``false``. If set to ``true`` the node will never be selected as a synchronous replica.
|
||||
|
||||
+7
-5
@@ -18,9 +18,11 @@
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#
|
||||
import os
|
||||
# import sys
|
||||
# sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, os.path.abspath('..'))
|
||||
|
||||
from patroni.version import __version__
|
||||
|
||||
# -- General configuration ------------------------------------------------
|
||||
|
||||
@@ -51,7 +53,7 @@ master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = 'Patroni'
|
||||
copyright = '2016, Zalando SE'
|
||||
copyright = '2015 Compose, Zalando SE'
|
||||
author = 'Zalando SE'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
@@ -59,9 +61,9 @@ author = 'Zalando SE'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '1.2'
|
||||
version = __version__[:__version__.rfind('.')]
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '1.2.2'
|
||||
release = __version__
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
@@ -14,11 +14,11 @@ Patroni configuration is stored in the DCS (Distributed Configuration Store). Th
|
||||
|
||||
- Local :ref:`configuration <settings>` (patroni.yml).
|
||||
These options are defined in the configuration file and take precedence over dynamic configuration.
|
||||
patroni.yml could be changed and reload in runtime (without restart of Patroni) by sending SIGHUP to the Patroni process or by performing ``POST /reload`` REST-API request.
|
||||
patroni.yml could be changed and reloaded in runtime (without restart of Patroni) by sending SIGHUP to the Patroni process, performing ``POST /reload`` REST-API request or executing ``patronictl reload``.
|
||||
|
||||
- Environment :ref:`configuration <environment>` .
|
||||
- Environment :ref:`configuration <environment>`.
|
||||
It is possible to set/override some of the "Local" configuration parameters with environment variables.
|
||||
Environment configuration is very useful when you are running in a dynamic environment and you don't know some of the parameters in advance (for example it's not possible to know you external IP address when you are running inside ``docker``).
|
||||
Environment configuration is very useful when you are running in a dynamic environment and you don't know some of the parameters in advance (for example it's not possible to know your external IP address when you are running inside ``docker``).
|
||||
|
||||
Some of the PostgreSQL parameters must hold the same values on the master and the replicas. For those, values set either in the local patroni configuration files or via the environment variables take no effect. To alter or set their values one must change the shared configuration in the DCS. Below is the actual list of such parameters together with the default values:
|
||||
|
||||
@@ -42,7 +42,7 @@ There are some other Postgres parameters controlled by Patroni:
|
||||
|
||||
- listen_addresses - is set either from ``postgresql.listen`` or from ``PATRONI_POSTGRESQL_LISTEN`` environment variable
|
||||
- port - is set either from ``postgresql.listen`` or from ``PATRONI_POSTGRESQL_LISTEN`` environment variable
|
||||
- cluster_name - is set either from ``scope`` or from ``PATRRONI_SCOPE`` environment variable
|
||||
- cluster_name - is set either from ``scope`` or from ``PATRONI_SCOPE`` environment variable
|
||||
- hot_standby: on
|
||||
|
||||
To be on the safe side parameters from the above lists are not written into ``postgresql.conf``, but passed as a list of arguments to the ``pg_ctl start`` which gives them the highest precedence, even above `ALTER SYSTEM <https://www.postgresql.org/docs/current/static/sql-altersystem.html>`__
|
||||
@@ -76,153 +76,11 @@ Also, the following Patroni configuration options can be changed only dynamicall
|
||||
- loop_wait: 10
|
||||
- retry_timeouts: 10
|
||||
- maximum_lag_on_failover: 1048576
|
||||
- max_timelines_history: 0
|
||||
- check_timeline: false
|
||||
- postgresql.use_slots: true
|
||||
|
||||
Upon changing these options, Patroni will read the relevant section of the configuration stored in DCS and change its
|
||||
run-time values.
|
||||
|
||||
Patroni nodes are dumping the state of the DCS options to disk upon for every change of the configuration into the file ``patroni.dynamic.json`` located in the Postgres data directory. Only the master is allowed to restore these options from the on-disk dump if these are completely absent from the DCS or if they are invalid.
|
||||
|
||||
REST API
|
||||
========
|
||||
|
||||
We provide a REST API endpoint for working with dynamic configuration.
|
||||
|
||||
GET /config
|
||||
-----------
|
||||
Get current version of dynamic configuration.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 30,
|
||||
"loop_wait": 10,
|
||||
"retry_timeout": 10,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"use_pg_rewind": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"wal_log_hints": "on",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"max_wal_senders": 5,
|
||||
"max_replication_slots": 5,
|
||||
"max_connections": "100"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PATCH /config
|
||||
-------------
|
||||
Change existing configuration.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s -XPATCH -d \
|
||||
'{"loop_wait":5,"ttl":20,"postgresql":{"parameters":{"max_connections":"101"}}}' \
|
||||
http://localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 20,
|
||||
"loop_wait": 5,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"retry_timeout": 10,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"use_pg_rewind": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"wal_log_hints": "on",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"max_wal_senders": 5,
|
||||
"max_replication_slots": 5,
|
||||
"max_connections": "101"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The above REST API call patches the existing configuration and returns the new configuration.
|
||||
|
||||
Let's check that the node processed this configuration. First of all it should start printing log lines every 5 seconds (loop_wait=5). The change of "max_connections" requires a restart, so the "restart_pending" flag should be exposed:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8008/patroni | jq .
|
||||
{
|
||||
"pending_restart": true,
|
||||
"database_system_identifier": "6287881213849985952",
|
||||
"postmaster_start_time": "2016-06-13 13:13:05.211 CEST",
|
||||
"xlog": {
|
||||
"location": 2197818976
|
||||
},
|
||||
"patroni": {
|
||||
"scope": "batman",
|
||||
"version": "1.0"
|
||||
},
|
||||
"state": "running",
|
||||
"role": "master",
|
||||
"server_version": 90503
|
||||
}
|
||||
|
||||
Removing parameters:
|
||||
|
||||
If you want to remove (reset) some setting just patch it with ``null``:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s -XPATCH -d \
|
||||
'{"postgresql":{"parameters":{"max_connections":null}}}' \
|
||||
http://localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 20,
|
||||
"loop_wait": 5,
|
||||
"retry_timeout": 10,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"use_pg_rewind": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"unix_socket_directories": ".",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"wal_log_hints": "on",
|
||||
"max_wal_senders": 5,
|
||||
"max_replication_slots": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Above call removes ``postgresql.parameters.max_connections`` from the dynamic configuration.
|
||||
|
||||
PUT /config
|
||||
-----------
|
||||
|
||||
It's also possible to perform the full rewrite of an existing dynamic configuration unconditionally:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s -XPUT -d \
|
||||
'{"maximum_lag_on_failover":1048576,"retry_timeout":10,"postgresql":{"use_slots":true,"use_pg_rewind":true,"parameters":{"hot_standby":"on","wal_log_hints":"on","wal_keep_segments":8,"wal_level":"hot_standby","unix_socket_directories":".","max_wal_senders":5}},"loop_wait":3,"ttl":20}' \
|
||||
http://localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 20,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"retry_timeout": 10,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"unix_socket_directories": ".",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"wal_log_hints": "on",
|
||||
"max_wal_senders": 5
|
||||
},
|
||||
"use_pg_rewind": true
|
||||
},
|
||||
"loop_wait": 3
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
.. _existing_data:
|
||||
|
||||
Convert a Standalone to a Patroni Cluster
|
||||
=========================================
|
||||
|
||||
This section describes the process for converting a standalone PostgreSQL instance into a Patroni cluster.
|
||||
|
||||
To deploy a Patroni cluster without using a pre-existing PostgreSQL instance, see :ref:`Running and Configuring <running_configuring>` instead.
|
||||
|
||||
Procedure
|
||||
---------
|
||||
|
||||
A Patroni cluster can be started with a data directory from a single-node PostgreSQL database. This is achieved by following closely these steps:
|
||||
|
||||
1. Manually start PostgreSQL daemon
|
||||
2. Create Patroni superuser and replication users as defined in the :ref:`authentication <postgresql_settings>` section of the Patroni configuration. If this user is created in SQL, the following queries achieve this:
|
||||
|
||||
.. code-block:: sql
|
||||
|
||||
CREATE USER $PATRONI_SUPERUSER_USERNAME WITH SUPERUSER ENCRYPTED PASSWORD '$PATRONI_SUPERUSER_PASSWORD';
|
||||
CREATE USER $PATRONI_REPLICATION_USERNAME WITH REPLICATION ENCRYPTED PASSWORD '$PATRONI_REPLICATION_PASSWORD';
|
||||
|
||||
3. Start Patroni (e.g. ``patroni /etc/patroni/patroni.yml``). It automatically detects that PostgreSQL daemon is already running but its configuration might be out-of-date.
|
||||
4. Ask Patroni to restart the node with ``patronictl restart cluster-name node-name``. This step is only required if PostgreSQL configuration is out-of-date.
|
||||
|
||||
|
||||
FAQ
|
||||
---
|
||||
|
||||
- During Patroni startup, Patroni complains that it cannot bind to the PostgreSQL port.
|
||||
|
||||
You need to verify ``listen_addresses`` and ``port`` in ``postgresql.conf`` and ``postgresql.listen`` in ``patroni.yml``. Don't forget that ``pg_hba.conf`` should allow such access.
|
||||
|
||||
- After asking Patroni to restart the node, PostgreSQL displays the error message ``could not open configuration file "/etc/postgresql/10/main/pg_hba.conf": No such file or directory``
|
||||
|
||||
It can mean various things depending on how you manage PostgreSQL configuration. If you specified `postgresql.config_dir`, Patroni generates the ``pg_hba.conf`` based on the settings in the :ref:`bootstrap <bootstrap_settings>` section only when it bootstraps a new cluster. In this scenario the ``PGDATA`` was not empty, therefore no bootstrap happened. This file must exist beforehand.
|
||||
+6
-4
@@ -6,11 +6,11 @@
|
||||
Introduction
|
||||
============
|
||||
|
||||
Patroni is a template for you to create your own customized, high-availability solution using Python and - for maximum accessibility - a distributed configuration store like `ZooKeeper <https://zookeeper.apache.org/>`__, `etcd <https://github.com/coreos/etcd>`__ or `Consul <https://github.com/hashicorp/consul>`__. Database engineers, DBAs, DevOps engineers, and SREs who are looking to quickly deploy HA PostgreSQL in the datacenter-or anywhere else-will hopefully find it useful.
|
||||
Patroni is a template for you to create your own customized, high-availability solution using Python and - for maximum accessibility - a distributed configuration store like `ZooKeeper <https://zookeeper.apache.org/>`__, `etcd <https://github.com/coreos/etcd>`__, `Consul <https://github.com/hashicorp/consul>`__ or `Kubernetes <https://kubernetes.io>`__. Database engineers, DBAs, DevOps engineers, and SREs who are looking to quickly deploy HA PostgreSQL in the datacenter-or anywhere else-will hopefully find it useful.
|
||||
|
||||
We call Patroni a "template" because it is far from being a one-size-fits-all or plug-and-play replication system. It will have its own caveats. Use wisely. There are many ways to run high availability with PostgreSQL; for a list, see the `PostgreSQL Documentation <https://wiki.postgresql.org/wiki/Replication,_Clustering,_and_Connection_Pooling>`__.
|
||||
|
||||
**Note to Kubernetes users**: We're currently developing Patroni to be as useful as possible for teams running Kubernetes on top of Google Compute Engine; Patroni can be the HA solution for Postgres in such an environment. To this end, we've created a `Helm Chart <https://github.com/kubernetes/charts/tree/master/incubator/patroni>`__ that enables you to deploy a five-node Patroni cluster using a Kubernetes PetSet.
|
||||
**Note to Kubernetes users**: Patroni can run natively on top of Kubernetes. Take a look at the :ref:`Kubernetes <kubernetes>` chapter of the Patroni documentation.
|
||||
|
||||
|
||||
.. toctree::
|
||||
@@ -19,10 +19,14 @@ We call Patroni a "template" because it is far from being a one-size-fits-all or
|
||||
|
||||
README
|
||||
dynamic_configuration
|
||||
rest_api
|
||||
ENVIRONMENT
|
||||
SETTINGS
|
||||
replica_bootstrap
|
||||
replication_modes
|
||||
pause
|
||||
kubernetes
|
||||
watchdog
|
||||
releases
|
||||
CONTRIBUTING
|
||||
|
||||
@@ -32,5 +36,3 @@ Indices and tables
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
.. _kubernetes:
|
||||
|
||||
Using Patroni with Kubernetes
|
||||
=============================
|
||||
|
||||
Patroni can use Kubernetes objects in order to store the state of the cluster and manage the leader key. That makes it
|
||||
capable of operating Postgres in Kubernetes environment without any consistency store, namely, one doesn't
|
||||
need to run an extra Etcd deployment. There are two different type of Kubernetes objects Patroni can use to store the
|
||||
leader and the configuration keys, they are configured with the `kubernetes.use_endpoints` or `PATRONI_KUBERNETES_USE_ENDPOINTS`
|
||||
environment variable.
|
||||
|
||||
Use Endpoints
|
||||
-------------
|
||||
|
||||
Despite the fact that this is the recommended mode, it is turned off by default for compatibility reasons. When it is on, Patroni stores
|
||||
the cluster configuration and the leader key in the `metadata: annotations` fields of the respective `Endpoints` it creates.
|
||||
Changing the leader is safer than when using `ConfigMaps`, since both the annotations, containing the leader information, and the actual addresses
|
||||
pointing to the running leader pod are updated simultaneously in one go.
|
||||
|
||||
Use ConfigMaps
|
||||
--------------
|
||||
|
||||
In this mode, Patroni will create ConfigMaps instead of Endpoints and store keys inside meta-data of those ConfigMaps.
|
||||
Changing the leader takes at least two updates, one to the leader ConfigMap and another to the respective Endpoint.
|
||||
|
||||
There are two ways to direct the traffic to the Postgres master:
|
||||
|
||||
- use the `callback script <https://github.com/zalando/patroni/blob/master/kubernetes/callback.py>`_ provided by Patroni
|
||||
- configure the Kubernetes Postgres service to use the label selector with the `role_label` (configured in patroni configuration).
|
||||
|
||||
Note that in some cases, for instance, when running on OpenShift, there is no alternative to using ConfigMaps.
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
|
||||
Patroni Kubernetes :ref:`settings <kubernetes_settings>` and :ref:`environment variables <kubernetes_environment>` are described in the general chapters of the documentation.
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
- The `kubernetes <https://github.com/zalando/patroni/tree/master/kubernetes>`__ folder of the Patroni repository contains
|
||||
examples of the Docker image, the Kubernetes manifest and the callback script in order to test Patroni Kubernetes setup.
|
||||
Note that in the current state it will not be able to use PersistentVolumes because of permission issues.
|
||||
|
||||
- You can find the full-featured Docker image that can use Persistent Volumes in the
|
||||
`Spilo Project <https://github.com/zalando/spilo>`_.
|
||||
|
||||
- There is also a `Helm chart <https://github.com/kubernetes/charts/tree/master/incubator/patroni>`_
|
||||
to deploy the Spilo image configured with Patroni running using Kubernetes.
|
||||
|
||||
- In order to run your database clusters at scale using Patroni and Spilo, take a look at the
|
||||
`postgres-operator <https://github.com/zalando-incubator/postgres-operator>`_ project. It implements the operator pattern
|
||||
to manage Spilo clusters.
|
||||
+1
-1
@@ -25,7 +25,7 @@ When Patroni runs in a paused mode, it does not change the state of PostgreSQL,
|
||||
|
||||
- If there is no leader lock in the cluster, the running master acquires the lock. If there is more than one master node, then the first master to acquire the lock wins. If there are no masters altogether, Patroni does not try to promote any replicas. There is an exception in this rule: if there is no leader lock because the old master has demoted itself due to the manual promotion, then only the candidate node mentioned in the promotion request may take the leader lock. When the new leader lock is granted (i.e. after promoting a replica manually), Patroni makes sure the replicas that were streaming from the previous leader will switch to the new one.
|
||||
|
||||
- When Postgres is stopped, Patroni does not try to start it. When Patroni is stopped, it does not to stop Postgres instance it is managing.
|
||||
- When Postgres is stopped, Patroni does not try to start it. When Patroni is stopped, it does not try to stop the Postgres instance it is managing.
|
||||
|
||||
User guide
|
||||
----------
|
||||
|
||||
+1304
-1
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,207 @@
|
||||
Replica imaging and bootstrap
|
||||
=============================
|
||||
|
||||
Patroni allows customizing creation of a new replica. It also supports defining what happens when the new empty cluster
|
||||
is being bootstrapped. The distinction between two is well defined: Patroni creates replicas only if the ``initialize``
|
||||
key is present in DCS for the cluster. If there is no ``initialize`` key - Patroni calls bootstrap exclusively on the
|
||||
first node that takes the initialize key lock.
|
||||
|
||||
.. _custom_bootstrap:
|
||||
|
||||
Bootstrap
|
||||
---------
|
||||
|
||||
PostgreSQL provides ``initdb`` command to initialize a new cluster and Patroni calls it by default. In certain cases,
|
||||
particularly when creating a new cluster as a copy of an existing one, it is necessary to replace a built-in method with
|
||||
custom actions. Patroni supports executing user-defined scripts to bootstrap new clusters, supplying some required
|
||||
arguments to them, i.e. the name of the cluster and the path to the data directory. This is configured in the
|
||||
``bootstrap`` section of the Patroni configuration. For example:
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
bootstrap:
|
||||
method: <custom_bootstrap_method_name>
|
||||
<custom_bootstrap_method_name>:
|
||||
command: <path_to_custom_bootstrap_script> [param1 [, ...]]
|
||||
keep_existing_recovery_conf: False
|
||||
recovery_conf:
|
||||
recovery_target_action: promote
|
||||
recovery_target_timeline: latest
|
||||
restore_command: <method_specific_restore_command>
|
||||
|
||||
|
||||
Each bootstrap method must define at least a ``name`` and a ``command``. A special ``initdb`` method is available to trigger
|
||||
the default behavior, in which case ``method`` parameter can be omitted altogether. The ``command`` can be specified using either
|
||||
an absolute path, or the one relative to the ``patroni`` command location. In addition to the fixed parameters defined
|
||||
in the configuration files, Patroni supplies two cluster-specific ones:
|
||||
|
||||
--scope
|
||||
Name of the cluster to be bootstrapped
|
||||
--datadir
|
||||
Path to the data directory of the cluster instance to be bootstrapped
|
||||
|
||||
If the bootstrap script returns 0, Patroni tries to configure and start the PostgreSQL instance produced by it. If any
|
||||
of the intermediate steps fail, or the script returns a non-zero value, Patroni assumes that the bootstrap has failed,
|
||||
cleans up after itself and releases the initialize lock to give another node the opportunity to bootstrap.
|
||||
|
||||
If a ``recovery_conf`` block is defined in the same section as the custom bootstrap method, Patroni will generate a
|
||||
``recovery.conf`` before starting the newly bootstrapped instance. Typically, such recovery.conf should contain at least
|
||||
one of the ``recovery_target_*`` parameters, together with the ``recovery_target_timeline`` set to ``promote``.
|
||||
|
||||
If ``keep_existing_recovery_conf`` is defined and set to ``True``, Patroni will not remove the existing ``recovery.conf`` file if it exists.
|
||||
This is useful when bootstrapping from a backup with tools like pgBackRest that generate the appropriate ``recovery.conf`` for you.
|
||||
|
||||
.. note:: Bootstrap methods are neither chained, nor fallen-back to the default one in case the primary one fails
|
||||
|
||||
|
||||
.. _custom_replica_creation:
|
||||
|
||||
Building replicas
|
||||
-----------------
|
||||
|
||||
Patroni uses tried and proven ``pg_basebackup`` in order to create new replicas. One downside of it is that it requires
|
||||
a running master node. Another one is the lack of 'on-the-fly' compression for the backup data and no built-in cleanup
|
||||
for outdated backup files. Some people prefer other backup solutions, such as ``WAL-E``, ``pgBackRest``, ``Barman`` and
|
||||
others, or simply roll their own scripts. In order to accommodate all those use-cases Patroni supports running custom
|
||||
scripts to clone a new replica. Those are configured in the ``postgresql`` configuration block:
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
postgresql:
|
||||
create_replica_methods:
|
||||
- <method name>
|
||||
<method name>:
|
||||
command: <command name>
|
||||
keep_data: True
|
||||
no_params: True
|
||||
no_master: 1
|
||||
|
||||
example: wal_e
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
postgresql:
|
||||
create_replica_methods:
|
||||
- wal_e
|
||||
- basebackup
|
||||
wal_e:
|
||||
command: patroni_wale_restore
|
||||
no_master: 1
|
||||
envdir: {{WALE_ENV_DIR}}
|
||||
use_iam: 1
|
||||
basebackup:
|
||||
max-rate: '100M'
|
||||
|
||||
example: pgbackrest
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
postgresql:
|
||||
create_replica_methods:
|
||||
- pgbackrest
|
||||
- basebackup
|
||||
pgbackrest:
|
||||
command: /usr/bin/pgbackrest --stanza=<scope> --delta restore
|
||||
keep_data: True
|
||||
no_params: True
|
||||
basebackup:
|
||||
max-rate: '100M'
|
||||
|
||||
|
||||
The ``create_replica_methods`` defines available replica creation methods and the order of executing them. Patroni will
|
||||
stop on the first one that returns 0. Each method should define a separate section in the configuration file, listing the command
|
||||
to execute and any custom parameters that should be passed to that command. All parameters will be passed in a
|
||||
``--name=value`` format. Besides user-defined parameters, Patroni supplies a couple of cluster-specific ones:
|
||||
|
||||
--scope
|
||||
Which cluster this replica belongs to
|
||||
--datadir
|
||||
Path to the data directory of the replica
|
||||
--role
|
||||
Always 'replica'
|
||||
--connstring
|
||||
Connection string to connect to the cluster member to clone from (master or other replica). The user in the
|
||||
connection string can execute SQL and replication protocol commands.
|
||||
|
||||
A special ``no_master`` parameter, if defined, allows Patroni to call the replica creation method even if there is no
|
||||
running master or replicas. In that case, an empty string will be passed in a connection string. This is useful for
|
||||
restoring the formerly running cluster from the binary backup.
|
||||
|
||||
A special ``keep_data`` parameter, if defined, will instruct Patroni to not clean PGDATA folder before calling restore.
|
||||
|
||||
A special ``no_params`` parameter, if defined, restricts passing parameters to custom command.
|
||||
|
||||
A ``basebackup`` method is a special case: it will be used if
|
||||
``create_replica_methods`` is empty, although it is possible
|
||||
to list it explicitly among the ``create_replica_methods`` methods. This method initializes a new replica with the
|
||||
``pg_basebackup``, the base backup is taken from the master unless there are replicas with ``clonefrom`` tag, in which case one
|
||||
of such replicas will be used as the origin for pg_basebackup. It works without any configuration; however, it is
|
||||
possible to specify a ``basebackup`` configuration section. Same rules as with the other method configuration apply,
|
||||
namely, only long (with --) options should be specified there. Not all parameters make sense, if you override a connection
|
||||
string or provide an option to created tar-ed or compressed base backups, patroni won't be able to make a replica out
|
||||
of it. There is no validation performed on the names or values of the parameters passed to the ``basebackup`` section.
|
||||
You can specify basebackup parameters as either a map (key-value pairs) or a list of elements, where each element
|
||||
could be either a key-value pair or a single key (for options that does not receive any values, for instance, ``--verbose``).
|
||||
Consider those 2 examples:
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
postgresql:
|
||||
basebackup:
|
||||
max-rate: '100M'
|
||||
checkpoint: 'fast'
|
||||
|
||||
and
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
postgresql:
|
||||
basebackup:
|
||||
- verbose
|
||||
- max-rate: '100M'
|
||||
|
||||
If all replica creation methods fail, Patroni will try again all methods in order during the next event loop cycle.
|
||||
|
||||
.. _standby_cluster:
|
||||
|
||||
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 methods of creating a replica and
|
||||
recovery WAL records when a cluster is in the "standby mode" by providing
|
||||
`create_replica_methods` key in `standby_cluster` section. It is distinct from
|
||||
creating replicas, when cluster is detached and functions as a normal cluster,
|
||||
which is controlled by `create_replica_methods` in `postgresql` section. Both
|
||||
"standby" and "normal" `create_replica_methods` reference keys in `postgresql`
|
||||
section.
|
||||
|
||||
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
|
||||
create_replica_methods:
|
||||
- basebackup
|
||||
|
||||
Note, that these options will be applied only once during cluster bootstrap,
|
||||
and the only way to change them afterwards is through DCS.
|
||||
|
||||
If you use replication slots on the standby cluster, you must also create the corresponding replication slot on the primary cluster. It will not be done automatically by the standby cluster implementation. You can use Patroni's permanent replication slots feature on the primary cluster to maintain a replication slot with the same name as ``primary_slot_name``, or its default value if ``primary_slot_name`` is not provided.
|
||||
+25
-12
@@ -9,9 +9,11 @@ Patroni uses PostgreSQL streaming replication. For more information about stream
|
||||
Asynchronous mode durability
|
||||
----------------------------
|
||||
|
||||
In asynchronous mode the cluster is allowed to lose some committed transactions to ensure availability. When master server fails or becomes unavailable for any other reason Patroni will automatically promote a sufficiently healthy standby to master. Any transactions that have not been replicated to that standby remain in a "forked timeline" on the master, and are effectively unrecoverable [1]_.
|
||||
In asynchronous mode the cluster is allowed to lose some committed transactions to ensure availability. When the primary server fails or becomes unavailable for any other reason Patroni will automatically promote a sufficiently healthy standby to primary. Any transactions that have not been replicated to that standby remain in a "forked timeline" on the primary, and are effectively unrecoverable [1]_.
|
||||
|
||||
The amount of transactions that can be lost is controlled via ``maximum_lag_on_failover`` parameter. Because master transaction log position is not sampled in real time, in reality the amount of lost data on failover is worst case bounded by ``maximum_lag_on_failover`` bytes of transaction log plus the amount that is written in the last ``ttl`` seconds (``loop_wait``/2 seconds in the average case). However typical steady state replication delay is well under a second.
|
||||
The amount of transactions that can be lost is controlled via ``maximum_lag_on_failover`` parameter. Because the primary transaction log position is not sampled in real time, in reality the amount of lost data on failover is worst case bounded by ``maximum_lag_on_failover`` bytes of transaction log plus the amount that is written in the last ``ttl`` seconds (``loop_wait``/2 seconds in the average case). However typical steady state replication delay is well under a second.
|
||||
|
||||
By default, when running leader elections, Patroni does not take into account the current timeline of replicas, what in some cases could be undesirable behavior. You can prevent the node not having the same timeline as a former master become the new leader by changing the value of ``check_timeline`` parameter to ``true``.
|
||||
|
||||
PostgreSQL synchronous replication
|
||||
----------------------------------
|
||||
@@ -20,7 +22,7 @@ You can use Postgres's `synchronous replication <http://www.postgresql.org/docs/
|
||||
|
||||
In hosted datacenter environments (like AWS, Rackspace, or any network you do not control), synchronous replication significantly increases the variability of write performance. If followers become inaccessible from the leader, the leader effectively becomes read-only.
|
||||
|
||||
To enable a simple synchronous replication test, add the follow lines to the ``parameters`` section of your YAML configuration files:
|
||||
To enable a simple synchronous replication test, add the following lines to the ``parameters`` section of your YAML configuration files:
|
||||
|
||||
.. code:: YAML
|
||||
|
||||
@@ -29,28 +31,39 @@ To enable a simple synchronous replication test, add the follow lines to the ``p
|
||||
|
||||
When using PostgreSQL synchronous replication, use at least three Postgres data nodes to ensure write availability if one host fails.
|
||||
|
||||
Using PostgreSQL synchronous replication does not guarantee zero lost transactions under all circumstances. When master and standby that is currently acting as synchronous fail simultaneously a third node that might not contain all transactions will be promoted.
|
||||
Using PostgreSQL synchronous replication does not guarantee zero lost transactions under all circumstances. When the primary and the secondary that is currently acting as a synchronous replica fail simultaneously a third node that might not contain all transactions will be promoted.
|
||||
|
||||
.. _synchronous_mode:
|
||||
|
||||
Synchronous mode
|
||||
----------------
|
||||
|
||||
For use cases where losing committed transactions is not permissible you can turn on Patronis ``synchronous_mode``. When ``synchronous_mode`` is turned on Patroni will not promote a standby unless it is certain that the standby contains all transactions that may have returned a successful commit status to client [2]_. This means that the system may be unavailable for writes even though some servers are available. System administrators can still use manual failover commmands to promote a standby even if it results in transaction loss.
|
||||
For use cases where losing committed transactions is not permissible you can turn on Patroni's ``synchronous_mode``. When ``synchronous_mode`` is turned on Patroni will not promote a standby unless it is certain that the standby contains all transactions that may have returned a successful commit status to client [2]_. This means that the system may be unavailable for writes even though some servers are available. System administrators can still use manual failover commands to promote a standby even if it results in transaction loss.
|
||||
|
||||
Turning on ``synchronous_mode`` does not guarantee multi node durability of commits under all circumstances. When no suitable standby is available, master server will still accept writes, but does not guarantee their replication. When the master fails in this mode no standby will be promote. When the host that used to be master comes back it will get promoted automatically, unless system administrator performed a manual failover. This behavior makes synchronous mode usable with 2 node clusters.
|
||||
Turning on ``synchronous_mode`` does not guarantee multi node durability of commits under all circumstances. When no suitable standby is available, primary server will still accept writes, but does not guarantee their replication. When the primary fails in this mode no standby will be promoted. When the host that used to be the primary comes back it will get promoted automatically, unless system administrator performed a manual failover. This behavior makes synchronous mode usable with 2 node clusters.
|
||||
|
||||
When ``synchronous_mode`` is on and a standby crashes, commits will block until next iteration of Patroni runs and switches master to standalone mode (worst case delay for writes ``ttl`` seconds, average case ``loop_wait``/2 seconds). Manually shutting down or restarting a standby will not cause a commit service interruption. Standby will signal the master to release itself from synchronous standby duties before PostgreSQL shutdown is initiated.
|
||||
When ``synchronous_mode`` is on and a standby crashes, commits will block until next iteration of Patroni runs and switches the primary to standalone mode (worst case delay for writes ``ttl`` seconds, average case ``loop_wait``/2 seconds). Manually shutting down or restarting a standby will not cause a commit service interruption. Standby will signal the primary to release itself from synchronous standby duties before PostgreSQL shutdown is initiated.
|
||||
|
||||
When it is absolutely necessary to guarantee that each write is stored durably
|
||||
on at least two nodes, enable ``synchronous_mode_strict`` in addition to the
|
||||
``synchronous_mode``. This parameter prevents Patroni from switching off the
|
||||
synchronous replication on the primary when no synchronous standby candidates
|
||||
are available. As a downside, the primary is not be available for writes
|
||||
(unless the Postgres transaction explicitly turns of ``synchronous_mode``),
|
||||
blocking all client write requests until at least one synchronous replica comes
|
||||
up.
|
||||
|
||||
You can ensure that a standby never becomes the synchronous standby by setting ``nosync`` tag to true. This is recommended to set for standbys that are behind slow network connections and would cause performance degradation when becoming a synchronous standby.
|
||||
|
||||
Synchronous mode can be switched on and off via Patroni REST interface. See `dynamic configuration <https://github.com/zalando/patroni/blob/master/docs/dynamic_configuration.rst>`__ for instructions.
|
||||
Synchronous mode can be switched on and off via Patroni REST interface. See :ref:`dynamic configuration <dynamic_configuration>` for instructions.
|
||||
|
||||
Note: Because of the way synchronous replication is implemented in PostgreSQL it is still possible to lose transactions even when using ``synchronous_mode_strict``. If the PostgreSQL backend is cancelled while waiting to acknowledge replication (as a result of packet cancellation due to client timeout or backend failure) transaction changes become visible for other backends. Such changes are not yet replicated and may be lost in case of standby promotion.
|
||||
|
||||
|
||||
Synchronous mode implementation
|
||||
-------------------------------
|
||||
|
||||
When in synchronous mode Patroni maintains synchronization state in the DCS, containing the latest master and current synchronous standby. This state is updated with strict ordering constraints to ensure the following invariants:
|
||||
When in synchronous mode Patroni maintains synchronization state in the DCS, containing the latest primary and current synchronous standby. This state is updated with strict ordering constraints to ensure the following invariants:
|
||||
|
||||
- A node must be marked as the latest leader whenever it can accept write transactions. Patroni crashing or PostgreSQL not shutting down can cause violations of this invariant.
|
||||
|
||||
@@ -60,9 +73,9 @@ When in synchronous mode Patroni maintains synchronization state in the DCS, con
|
||||
|
||||
Patroni will only ever assign one standby to ``synchronous_standby_names`` because with multiple candidates it is not possible to know which node was acting as synchronous during the failure.
|
||||
|
||||
On each HA loop iteration Patroni re-evaluates synchronous standby choice. If the current synchronous standby is connected and has not requested its synchronous status to be removed it remains picked. Otherwise the cluster member avaiable for sync that is furthest ahead in replication is picked.
|
||||
On each HA loop iteration Patroni re-evaluates synchronous standby choice. If the current synchronous standby is connected and has not requested its synchronous status to be removed it remains picked. Otherwise the cluster member available for sync that is furthest ahead in replication is picked.
|
||||
|
||||
|
||||
.. [1] The data is still there, but recovering it requires a manual recovery effort by data recovery specialists. When Patroni is allowed to rewind with ``use_pg_rewind`` the forked timeline will be automatically erased to rejoin the failed master with the cluster.
|
||||
.. [1] The data is still there, but recovering it requires a manual recovery effort by data recovery specialists. When Patroni is allowed to rewind with ``use_pg_rewind`` the forked timeline will be automatically erased to rejoin the failed primary with the cluster.
|
||||
|
||||
.. [2] Clients can change the behavior per transaction using PostgreSQL's ``synchronous_commit`` setting. Transactions with ``synchronous_commit`` values of ``off`` and ``local`` may be lost on fail over, but will not be blocked by replication delays.
|
||||
.. [2] Clients can change the behavior per transaction using PostgreSQL's ``synchronous_commit`` setting. Transactions with ``synchronous_commit`` values of ``off`` and ``local`` may be lost on fail over, but will not be blocked by replication delays.
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
.. _rest_api:
|
||||
|
||||
Patroni REST API
|
||||
================
|
||||
|
||||
Patroni has a rich REST API, which is used by Patroni itself during the leader race, by the ``patronictl`` tool in order to perform failovers/switchovers/reinitialize/restarts/reloads, by HAProxy or any other kind of load balancer to perform HTTP health checks, and of course could also be used for monitoring. Below you will find the list of Patroni REST API endpoints.
|
||||
|
||||
Health check endpoints
|
||||
----------------------
|
||||
For all health check ``GET`` requests Patroni returns a JSON document with the status of the node, along with the HTTP status code. If you don't want or don't need the JSON document, you might consider using the ``OPTIONS`` method instead of ``GET``.
|
||||
|
||||
- The following requests to Patroni REST API will return HTTP status code **200** only when the Patroni node is running as the leader:
|
||||
|
||||
- ``GET /``
|
||||
- ``GET /master``
|
||||
- ``GET /leader``
|
||||
- ``GET /primary``
|
||||
- ``GET /read-write``
|
||||
|
||||
- ``GET /replica``: replica health check endpoint. It returns HTTP status code **200** only when the Patroni node is in the state ``running``, the role is ``replica`` and ``noloadbalance`` tag is not set.
|
||||
|
||||
- ``GET /read-only``: like the above endpoint, but also includes the primary.
|
||||
|
||||
- ``GET /standby-leader``: returns HTTP status code **200** only when the Patroni node is running as the leader in a :ref:`standby cluster <standby_cluster>`.
|
||||
|
||||
- ``GET /synchronous`` or ``GET /sync``: returns HTTP status code **200** only when the Patroni node is running as a synchronous standby.
|
||||
|
||||
- ``GET /asynchronous`` or ``GET /async``: returns HTTP status code **200** only when the Patroni node is running as an asynchronous standby.
|
||||
|
||||
- ``GET /health``: returns HTTP status code **200** only when PostgreSQL is up and running.
|
||||
|
||||
Monitoring endpoint
|
||||
-------------------
|
||||
|
||||
The ``GET /patroni`` is used by Patroni during the leader race. It also could be used by your monitoring system. The JSON document produced by this endpoint has the same structure as the JSON produced by the health check endpoints.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8008/patroni | jq .
|
||||
{
|
||||
"state": "running",
|
||||
"postmaster_start_time": "2019-09-24 09:22:32.555 CEST",
|
||||
"role": "master",
|
||||
"server_version": 110005,
|
||||
"cluster_unlocked": false,
|
||||
"xlog": {
|
||||
"location": 25624640
|
||||
},
|
||||
"timeline": 3,
|
||||
"database_system_identifier": "6739877027151648096",
|
||||
"patroni": {
|
||||
"version": "1.6.0",
|
||||
"scope": "batman"
|
||||
}
|
||||
}
|
||||
|
||||
Cluster status endpoints
|
||||
------------------------
|
||||
|
||||
- The ``GET /cluster`` endpoint generates a JSON document describing the current cluster topology and state:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8008/cluster | jq .
|
||||
{
|
||||
"members": [
|
||||
{
|
||||
"name": "postgresql0",
|
||||
"host": "127.0.0.1",
|
||||
"port": 5432,
|
||||
"role": "leader",
|
||||
"state": "running",
|
||||
"api_url": "http://127.0.0.1:8008/patroni",
|
||||
"timeline": 5,
|
||||
"tags": {
|
||||
"clonefrom": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "postgresql1",
|
||||
"host": "127.0.0.1",
|
||||
"port": 5433,
|
||||
"role": "replica",
|
||||
"state": "running",
|
||||
"api_url": "http://127.0.0.1:8009/patroni",
|
||||
"timeline": 5,
|
||||
"tags": {
|
||||
"clonefrom": true
|
||||
},
|
||||
"lag": 0
|
||||
}
|
||||
],
|
||||
"scheduled_switchover": {
|
||||
"at": "2019-09-24T10:36:00+02:00",
|
||||
"from": "postgresql0"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
- The ``GET /history`` endpoint provides a view on the history of cluster switchovers/failovers. The format is very similar to the content of history files in the ``pg_wal`` directory. The only difference is the timestamp field showing when the new timeline was created.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8008/history | jq .
|
||||
[
|
||||
[
|
||||
1,
|
||||
25623960,
|
||||
"no recovery target specified",
|
||||
"2019-09-23T16:57:57+02:00"
|
||||
],
|
||||
[
|
||||
2,
|
||||
25624344,
|
||||
"no recovery target specified",
|
||||
"2019-09-24T09:22:33+02:00"
|
||||
],
|
||||
[
|
||||
3,
|
||||
25624752,
|
||||
"no recovery target specified",
|
||||
"2019-09-24T09:26:15+02:00"
|
||||
],
|
||||
[
|
||||
4,
|
||||
50331856,
|
||||
"no recovery target specified",
|
||||
"2019-09-24T09:35:52+02:00"
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
Config endpoint
|
||||
---------------
|
||||
|
||||
``GET /config``: Get the current version of the dynamic configuration:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 30,
|
||||
"loop_wait": 10,
|
||||
"retry_timeout": 10,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"use_pg_rewind": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"wal_log_hints": "on",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"max_wal_senders": 5,
|
||||
"max_replication_slots": 5,
|
||||
"max_connections": "100"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
``PATCH /config``: Change the existing configuration.
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s -XPATCH -d \
|
||||
'{"loop_wait":5,"ttl":20,"postgresql":{"parameters":{"max_connections":"101"}}}' \
|
||||
http://localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 20,
|
||||
"loop_wait": 5,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"retry_timeout": 10,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"use_pg_rewind": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"wal_log_hints": "on",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"max_wal_senders": 5,
|
||||
"max_replication_slots": 5,
|
||||
"max_connections": "101"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The above REST API call patches the existing configuration and returns the new configuration.
|
||||
|
||||
Let's check that the node processed this configuration. First of all it should start printing log lines every 5 seconds (loop_wait=5). The change of "max_connections" requires a restart, so the "pending_restart" flag should be exposed:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8008/patroni | jq .
|
||||
{
|
||||
"pending_restart": true,
|
||||
"database_system_identifier": "6287881213849985952",
|
||||
"postmaster_start_time": "2016-06-13 13:13:05.211 CEST",
|
||||
"xlog": {
|
||||
"location": 2197818976
|
||||
},
|
||||
"patroni": {
|
||||
"scope": "batman",
|
||||
"version": "1.0"
|
||||
},
|
||||
"state": "running",
|
||||
"role": "master",
|
||||
"server_version": 90503
|
||||
}
|
||||
|
||||
Removing parameters:
|
||||
|
||||
If you want to remove (reset) some setting just patch it with ``null``:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s -XPATCH -d \
|
||||
'{"postgresql":{"parameters":{"max_connections":null}}}' \
|
||||
http://localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 20,
|
||||
"loop_wait": 5,
|
||||
"retry_timeout": 10,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"use_pg_rewind": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"unix_socket_directories": ".",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"wal_log_hints": "on",
|
||||
"max_wal_senders": 5,
|
||||
"max_replication_slots": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
The above call removes ``postgresql.parameters.max_connections`` from the dynamic configuration.
|
||||
|
||||
``PUT /config``: It's also possible to perform the full rewrite of an existing dynamic configuration unconditionally:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s -XPUT -d \
|
||||
'{"maximum_lag_on_failover":1048576,"retry_timeout":10,"postgresql":{"use_slots":true,"use_pg_rewind":true,"parameters":{"hot_standby":"on","wal_log_hints":"on","wal_keep_segments":8,"wal_level":"hot_standby","unix_socket_directories":".","max_wal_senders":5}},"loop_wait":3,"ttl":20}' \
|
||||
http://localhost:8008/config | jq .
|
||||
{
|
||||
"ttl": 20,
|
||||
"maximum_lag_on_failover": 1048576,
|
||||
"retry_timeout": 10,
|
||||
"postgresql": {
|
||||
"use_slots": true,
|
||||
"parameters": {
|
||||
"hot_standby": "on",
|
||||
"unix_socket_directories": ".",
|
||||
"wal_keep_segments": 8,
|
||||
"wal_level": "hot_standby",
|
||||
"wal_log_hints": "on",
|
||||
"max_wal_senders": 5
|
||||
},
|
||||
"use_pg_rewind": true
|
||||
},
|
||||
"loop_wait": 3
|
||||
}
|
||||
|
||||
|
||||
Switchover and failover endpoints
|
||||
---------------------------------
|
||||
|
||||
``POST /switchover`` or ``POST /failover``. These endpoints are very similar to each other. There are a couple of minor differences though:
|
||||
|
||||
1. The failover endpoint allows to perform a manual failover when there are no healthy nodes, but at the same time it will not allow you to schedule a switchover.
|
||||
|
||||
2. The switchover endpoint is the opposite. It works only when the cluster is healthy (there is a leader) and allows to schedule a switchover at a given time.
|
||||
|
||||
|
||||
In the JSON body of the ``POST`` request you must specify at least the ``leader`` or ``candidate`` fields and optionally the ``scheduled_at`` field if you want to schedule a switchover at a specific time.
|
||||
|
||||
|
||||
Example: perform a failover to the specific node:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8009/failover -XPOST -d '{"candidate":"postgresql1"}'
|
||||
Successfully failed over to "postgresql1"
|
||||
|
||||
|
||||
Example: schedule a switchover from the leader to any other healthy replica in the cluster at a specific time:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
$ curl -s http://localhost:8008/switchover -XPOST -d \
|
||||
'{"leader":"postgresql0","scheduled_at":"2019-09-24T12:00+00"}'
|
||||
Switchover scheduled
|
||||
|
||||
|
||||
Depending on the situation the request might finish with a different HTTP status code and body. The status code **200** is returned when the switchover or failover successfully completed. If the switchover was successfully scheduled, Patroni will return HTTP status code **202**. In case something went wrong, the error status code (one of **400**, **412** or **503**) will be returned with some details in the response body. For more information please check the source code of ``patroni/api.py:do_POST_failover()`` method.
|
||||
|
||||
- ``DELETE /switchover``: delete the scheduled switchover
|
||||
|
||||
The ``POST /switchover`` and ``POST failover`` endpoints are used by ``patronictl switchover`` and ``patronictl failover``, respectively.
|
||||
The ``DELETE /switchover`` is used by ``patronictl flush <cluster-name> switchover``.
|
||||
|
||||
|
||||
Restart endpoint
|
||||
----------------
|
||||
|
||||
- ``POST /restart``: You can restart Postgres on the specific node by performing the ``POST /restart`` call. In the JSON body of ``POST`` request it is possible to optionally specify some restart conditions:
|
||||
|
||||
- **restart_pending**: boolean, if set to ``true`` Patroni will restart PostgreSQL only when restart is pending in order to apply some changes in the PostgreSQL config.
|
||||
- **role**: perform restart only if the current role of the node matches with the role from the POST request.
|
||||
- **postgres_version**: perform restart only if the current version of postgres is smaller than specified in the POST request.
|
||||
- **timeout**: how long we should wait before PostgreSQL starts accepting connections. Overrides ``master_start_timeout``.
|
||||
- **schedule**: timestamp with time zone, schedule the restart somewhere in the future.
|
||||
|
||||
- ``DELETE /restart``: delete the scheduled restart
|
||||
|
||||
``POST /restart`` and ``DELETE /restart`` endpoints are used by ``patronictl restart`` and ``patronictl flush <cluster-name> restart`` respectively.
|
||||
|
||||
|
||||
Reload endpoint
|
||||
---------------
|
||||
|
||||
The ``POST /reload`` call will order Patroni to re-read and apply the configuration file. This is the equivalent of sending the ``SIGHUP`` signal to the Patroni process. In case you changed some of the Postgres parameters which require a restart (like **shared_buffers**), you still have to explicitly do the restart of Postgres by either calling the ``POST /restart`` endpoint or with the help of ``patronictl restart``.
|
||||
|
||||
The reload endpoint is used by ``patronictl reload``.
|
||||
|
||||
|
||||
Reinitialize endpoint
|
||||
---------------------
|
||||
|
||||
``POST /reinitialize``: reinitialize the PostgreSQL data directory on the specified node. It is allowed to be executed only on replicas. Once called, it will remove the data directory and start ``pg_basebackup`` or some alternative :ref:`replica creation method <custom_replica_creation>`.
|
||||
|
||||
The call might fail if Patroni is in a loop trying to recover (restart) a failed Postgres. In order to overcome this problem one can specify ``{"force":true}`` in the request body.
|
||||
|
||||
The reinitialize endpoint is used by ``patronictl reinit``.
|
||||
@@ -0,0 +1,39 @@
|
||||
.. _watchdog:
|
||||
|
||||
Watchdog support
|
||||
================
|
||||
|
||||
Having multiple PostgreSQL servers running as master can result in transactions lost due to diverging timelines. This situation is also called a split-brain problem. To avoid split-brain Patroni needs to ensure PostgreSQL will not accept any transaction commits after leader key expires in the DCS. Under normal circumstances Patroni will try to achieve this by stopping PostgreSQL when leader lock update fails for any reason. However, this may fail to happen due to various reasons:
|
||||
|
||||
- Patroni has crashed due to a bug, out-of-memory condition or by being accidentally killed by a system administrator.
|
||||
|
||||
- Shutting down PostgreSQL is too slow.
|
||||
|
||||
- Patroni does not get to run due to high load on the system, the VM being paused by the hypervisor, or other infrastructure issues.
|
||||
|
||||
To guarantee correct behavior under these conditions Patroni supports watchdog devices. Watchdog devices are software or hardware mechanisms that will reset the whole system when they do not get a keepalive heartbeat within a specified timeframe. This adds an additional layer of fail safe in case usual Patroni split-brain protection mechanisms fail.
|
||||
|
||||
Patroni will try to activate the watchdog before promoting PostgreSQL to master. If watchdog activation fails and watchdog mode is ``required`` then the node will refuse to become master. When deciding to participate in leader election Patroni will also check that watchdog configuration will allow it to become leader at all. After demoting PostgreSQL (for example due to a manual failover) Patroni will disable the watchdog again. Watchdog will also be disabled while Patroni is in paused state.
|
||||
|
||||
By default Patroni will set up the watchdog to expire 5 seconds before TTL expires. With the default setup of ``loop_wait=10`` and ``ttl=30`` this gives HA loop at least 15 seconds (``ttl`` - ``safety_margin`` - ``loop_wait``) to complete before the system gets forcefully reset. By default accessing DCS is configured to time out after 10 seconds. This means that when DCS is unavailable, for example due to network issues, Patroni and PostgreSQL will have at least 5 seconds (``ttl`` - ``safety_margin`` - ``loop_wait`` - ``retry_timeout``) to come to a state where all client connections are terminated.
|
||||
|
||||
Safety margin is the amount of time that Patroni reserves for time between leader key update and watchdog keepalive. Patroni will try to send a keepalive immediately after confirmation of leader key update. If Patroni process is suspended for extended amount of time at exactly the right moment the keepalive may be delayed for more than the safety margin without triggering the watchdog. This results in a window of time where watchdog will not trigger before leader key expiration, invalidating the guarantee. To be absolutely sure that watchdog will trigger under all circumstances set up the watchdog to expire after half of TTL by setting ``safety_margin`` to -1 to set watchdog timeout to ``ttl // 2``. If you need this guarantee you probably should increase ``ttl`` and/or reduce ``loop_wait`` and ``retry_timeout``.
|
||||
|
||||
Currently watchdogs are only supported using Linux watchdog device interface.
|
||||
|
||||
Setting up software watchdog on Linux
|
||||
-------------------------------------
|
||||
|
||||
Default Patroni configuration will try to use ``/dev/watchdog`` on Linux if it is accessible to Patroni. For most use cases using software watchdog built into the Linux kernel is secure enough.
|
||||
|
||||
To enable software watchdog issue the following commands as root before starting Patroni:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
modprobe softdog
|
||||
# Replace postgres with the user you will be running patroni under
|
||||
chown postgres /dev/watchdog
|
||||
|
||||
For testing it may be helpful to disable rebooting by adding ``soft_noboot=1`` to the modprobe command line. In this case the watchdog will just log a line in kernel ring buffer, visible via `dmesg`.
|
||||
|
||||
Patroni will log information about the watchdog when it is successfully enabled.
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
### confd
|
||||
|
||||
`confd` directory contains haproxy template files for the [confd](https://github.com/kelseyhightower/confd) -- lightweight configuration management tool
|
||||
`confd` directory contains haproxy and pgbouncer template files for the [confd](https://github.com/kelseyhightower/confd) -- lightweight configuration management tool
|
||||
You need to copy content of `confd` directory into /etcd/confd and run confd service:
|
||||
```bash
|
||||
$ confd -prefix=/service/$PATRONI_SCOPE -backend etcd -node $PATRONI_ETCD_HOST -interval=10
|
||||
$ confd -prefix=/service/$PATRONI_SCOPE -backend etcd -node $PATRONI_ETCD_URL -interval=10
|
||||
```
|
||||
It will periodically update haproxy.cfg with the actual list of Patroni nodes from `etcd` and "reload" haproxy when it is necessary.
|
||||
It will periodically update haproxy.cfg and pgbouncer.ini with the actual list of Patroni nodes from `etcd` and "reload" haproxy and pgbouncer.ini when it is necessary.
|
||||
|
||||
|
||||
### startup-scripts
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[template]
|
||||
prefix = "/service/batman"
|
||||
owner = "postgres"
|
||||
mode = "0644"
|
||||
src = "pgbouncer.tmpl"
|
||||
dest = "/etc/pgbouncer/pgbouncer.ini"
|
||||
|
||||
reload_cmd = "systemctl reload pgbouncer"
|
||||
|
||||
keys = [
|
||||
"/members/","/leader"
|
||||
]
|
||||
@@ -10,19 +10,23 @@ defaults
|
||||
timeout server 30m
|
||||
timeout check 5s
|
||||
|
||||
frontend master_postgresql
|
||||
listen stats
|
||||
mode http
|
||||
bind *:7000
|
||||
stats enable
|
||||
stats uri /
|
||||
|
||||
listen master
|
||||
bind *:5000
|
||||
default_backend backend_master
|
||||
|
||||
frontend replicas_postgresql
|
||||
bind *:5001
|
||||
default_backend backend_replicas
|
||||
|
||||
backend backend_master
|
||||
option httpchk OPTIONS /master
|
||||
http-check expect status 200
|
||||
default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
|
||||
{{range gets "/members/*"}} server {{base .Key}} {{$data := json .Value}}{{base (replace (index (split $data.conn_url "/") 2) "@" "/" -1)}} maxconn 100 check port {{index (split (index (split $data.api_url "/") 2) ":") 1}}
|
||||
{{end}}
|
||||
backend backend_replicas
|
||||
listen replicas
|
||||
bind *:5001
|
||||
option httpchk OPTIONS /replica
|
||||
http-check expect status 200
|
||||
default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
|
||||
{{range gets "/members/*"}} server {{base .Key}} {{$data := json .Value}}{{base (replace (index (split $data.conn_url "/") 2) "@" "/" -1)}} maxconn 100 check port {{index (split (index (split $data.api_url "/") 2) ":") 1}}
|
||||
{{end}}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[databases]
|
||||
{{with get "/leader"}}{{$leader := .Value}}{{$leadkey := printf "/members/%s" $leader}}{{with get $leadkey}}{{$data := json .Value}}{{$hostport := base (replace (index (split $data.conn_url "/") 2) "@" "/" -1)}}{{ $host := base (index (split $hostport ":") 0)}}{{ $port := base (index (split $hostport ":") 1)}}* = host={{ $host }} port={{ $port }} pool_size=10{{end}}{{end}}
|
||||
|
||||
[pgbouncer]
|
||||
logfile = /var/log/postgresql/pgbouncer.log
|
||||
pidfile = /var/run/postgresql/pgbouncer.pid
|
||||
listen_addr = *
|
||||
listen_port = 6432
|
||||
unix_socket_dir = /var/run/postgresql
|
||||
auth_type = trust
|
||||
auth_file = /etc/pgbouncer/userlist.txt
|
||||
auth_hba_file = /etc/pgbouncer/pg_hba.txt
|
||||
admin_users = pgbouncer
|
||||
stats_users = pgbouncer
|
||||
pool_mode = session
|
||||
max_client_conn = 100
|
||||
default_pool_size = 20
|
||||
@@ -11,3 +11,12 @@ Upstart job for Ubuntu 12.04 or 14.04. Requires Upstart > 1.4. Intended for sys
|
||||
|
||||
### patroni.service
|
||||
Systemd service file, to be copied to /etc/systemd/system/patroni.service, tested on Centos 7.1 with Patroni installed from pip.
|
||||
|
||||
### patroni
|
||||
Init.d service file for Debian-like distributions. Copy it to /etc/init.d/, make executable:
|
||||
```chmod 755 /etc/init.d/patroni``` and run with ```service patroni start```, or make it starting on boot with ```update-rc.d patroni defaults```. Also you might edit some configuration variables in it:
|
||||
PATRONI for patroni.py location
|
||||
CONF for configuration file
|
||||
LOGFILE for log (script creates it if does not exist)
|
||||
|
||||
Note. If you have several versions of Postgres installed, please add to POSTGRES_VERSION the release number which you wish to run. Script uses this value to append PATH environment with correct path to Postgres bin.
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
### BEGIN INIT INFO
|
||||
# Provides: patroni
|
||||
# Required-Start: $remote_fs $syslog
|
||||
# Required-Stop: $remote_fs $syslog
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: Patroni init script
|
||||
# Description: Runners to orchestrate a high-availability PostgreSQL
|
||||
### END INIT INFO
|
||||
|
||||
### BEGIN USER CONFIGURATION
|
||||
|
||||
CONF="/etc/patroni/postgres.yml"
|
||||
LOGFILE="/var/log/patroni.log"
|
||||
USER="postgres"
|
||||
GROUP="postgres"
|
||||
|
||||
NAME=patroni
|
||||
PATRONI="/opt/patroni/$NAME.py"
|
||||
PIDFILE="/var/run/$NAME.pid"
|
||||
|
||||
# Set this parameter, if you have several Postgres versions installed
|
||||
# POSTGRES_VERSION="9.4"
|
||||
POSTGRES_VERSION=""
|
||||
|
||||
### END USER CONFIGURATION
|
||||
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
# Loading this library for get_versions() function
|
||||
if test ! -e /usr/share/postgresql-common/init.d-functions; then
|
||||
log_failure_msg "Probably postgresql-common does not installed."
|
||||
exit 1
|
||||
else
|
||||
. /usr/share/postgresql-common/init.d-functions
|
||||
fi
|
||||
|
||||
# Is there Patroni executable?
|
||||
if test ! -e $PATRONI; then
|
||||
log_failure_msg "Patroni executable $PATRONI does not exist."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Is there Patroni configuration file?
|
||||
if test ! -e $CONF; then
|
||||
log_failure_msg "Patroni configuration file $CONF does not exist."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create logfile if doesn't exist
|
||||
if test ! -e $LOGFILE; then
|
||||
log_action_msg "Creating logfile for Patroni..."
|
||||
touch $LOGFILE
|
||||
chown $USER:$GROUP $LOGFILE
|
||||
fi
|
||||
|
||||
prepare_pgpath() {
|
||||
if [ "$POSTGRES_VERSION" != "" ]; then
|
||||
if [ -x /usr/lib/postgresql/$POSTGRES_VERSION/bin/pg_ctl ]; then
|
||||
PGPATH="/usr/lib/postgresql/$POSTGRES_VERSION/bin"
|
||||
else
|
||||
log_failure_msg "Postgres version incorrect, check POSTGRES_VERSION variable."
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
get_versions
|
||||
if echo $versions | grep -q -e "\s"; then
|
||||
log_warning_msg "You have several Postgres versions installed. Please, use POSTGRES_VERSION to define correct environment."
|
||||
else
|
||||
versions=`echo $versions | sed -e 's/^[ \t]*//'`
|
||||
PGPATH="/usr/lib/postgresql/$versions/bin"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
get_pid() {
|
||||
if test -e $PIDFILE; then
|
||||
PID=`cat $PIDFILE`
|
||||
CHILDPID=`ps --ppid $PID -o %p --no-headers`
|
||||
else
|
||||
log_failure_msg "Could not find PID file. Patroni probably down."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
prepare_pgpath
|
||||
PGPATH=$PATH:$PGPATH
|
||||
log_success_msg "Starting Patroni\n"
|
||||
exec start-stop-daemon --start --quiet \
|
||||
--background \
|
||||
--pidfile $PIDFILE --make-pidfile \
|
||||
--chuid $USER:$GROUP \
|
||||
--chdir `eval echo ~$USER` \
|
||||
--exec $PATRONI \
|
||||
--startas /bin/sh -- \
|
||||
-c "/usr/bin/env PATH=$PGPATH /usr/bin/python $PATRONI $CONF >> $LOGFILE 2>&1"
|
||||
;;
|
||||
|
||||
stop)
|
||||
log_success_msg "Stopping Patroni"
|
||||
get_pid
|
||||
start-stop-daemon --stop --pid $CHILDPID
|
||||
start-stop-daemon --stop --pidfile $PIDFILE --remove-pidfile --quiet
|
||||
;;
|
||||
|
||||
reload)
|
||||
log_success_msg "Reloading Patroni configuration"
|
||||
get_pid
|
||||
kill -HUP $CHILDPID
|
||||
;;
|
||||
|
||||
status)
|
||||
get_pid
|
||||
if start-stop-daemon -T --pid $CHILDPID; then
|
||||
log_success_msg "Patroni is running\n"
|
||||
exit 0
|
||||
else
|
||||
log_warning_msg "Patroni in not running\n"
|
||||
fi
|
||||
;;
|
||||
|
||||
restart)
|
||||
$0 stop
|
||||
$0 start
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Usage: /etc/init.d/$NAME {start|stop|restart|reload|status}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo .
|
||||
exit 0
|
||||
else
|
||||
echo " failed"
|
||||
exit 1
|
||||
fi
|
||||
@@ -11,17 +11,31 @@ Type=simple
|
||||
User=postgres
|
||||
Group=postgres
|
||||
|
||||
# Read in configuration file if it exists, otherwise proceed
|
||||
EnvironmentFile=-/etc/patroni_env.conf
|
||||
|
||||
WorkingDirectory=~
|
||||
|
||||
# Where to send early-startup messages from the server
|
||||
# This is normally controlled by the global default set by systemd
|
||||
# StandardOutput=syslog
|
||||
#StandardOutput=syslog
|
||||
|
||||
# Pre-commands to start watchdog device
|
||||
# Uncomment if watchdog is part of your patroni setup
|
||||
#ExecStartPre=-/usr/bin/sudo /sbin/modprobe softdog
|
||||
#ExecStartPre=-/usr/bin/sudo /bin/chown postgres /dev/watchdog
|
||||
|
||||
# Start the patroni process
|
||||
ExecStart=/bin/patroni /etc/patroni.yml
|
||||
|
||||
# Send HUP to reload from patroni.yml
|
||||
ExecReload=/bin/kill -s HUP $MAINPID
|
||||
|
||||
# only kill the patroni process, not it's children, so it will gracefully stop postgres
|
||||
KillMode=process
|
||||
|
||||
# Give a reasonable amount of time for the server to start up/shut down
|
||||
TimeoutSec=10
|
||||
TimeoutSec=30
|
||||
|
||||
# Do not restart the service if it crashes, we want to manually inspect database on failure
|
||||
Restart=no
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import argparse
|
||||
import shutil
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--dirname", required=True)
|
||||
parser.add_argument("--pathname", required=True)
|
||||
parser.add_argument("--filename", required=True)
|
||||
parser.add_argument("--mode", required=True, choices=("archive", "restore"))
|
||||
args, _ = parser.parse_known_args()
|
||||
|
||||
full_filename = os.path.join(args.dirname, args.filename)
|
||||
if args.mode == "archive":
|
||||
if not os.path.isdir(args.dirname):
|
||||
os.makedirs(args.dirname)
|
||||
if not os.path.exists(full_filename):
|
||||
shutil.copy(args.pathname, full_filename)
|
||||
else:
|
||||
shutil.copy(full_filename, args.pathname)
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env python
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--datadir", required=True)
|
||||
parser.add_argument("--dbname", required=True)
|
||||
parser.add_argument("--walmethod", required=True, choices=("fetch", "stream", "none"))
|
||||
args, _ = parser.parse_known_args()
|
||||
|
||||
walmethod = ["-X", args.walmethod] if args.walmethod != "none" else []
|
||||
sys.exit(subprocess.call(["pg_basebackup", "-D", args.datadir, "-c", "fast", "-d", args.dbname] + walmethod))
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
import argparse
|
||||
import shutil
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--datadir", required=True)
|
||||
parser.add_argument("--sourcedir", required=True)
|
||||
args, _ = parser.parse_known_args()
|
||||
|
||||
shutil.copytree(args.sourcedir, args.datadir)
|
||||
@@ -4,6 +4,7 @@ Feature: basic replication
|
||||
Scenario: check replication of a single table
|
||||
Given I start postgres0
|
||||
Then postgres0 is a leader after 10 seconds
|
||||
And there is a non empty initialize key in DCS after 15 seconds
|
||||
When I issue a PATCH request to http://127.0.0.1:8008/config with {"ttl": 20, "loop_wait": 2, "synchronous_mode": true}
|
||||
Then I receive a response code 200
|
||||
When I start postgres1
|
||||
@@ -14,19 +15,33 @@ Feature: basic replication
|
||||
Then table foo is present on postgres2 after 20 seconds
|
||||
|
||||
Scenario: check restart of sync replica
|
||||
Given I run patronictl.py restart batman postgres2 --force
|
||||
And "sync" key in DCS has sync_standby=postgres1 after 2 seconds
|
||||
And I run patronictl.py restart batman postgres1 --force
|
||||
Then I receive a response returncode 0
|
||||
And "sync" key in DCS has sync_standby=postgres2 after 10 seconds
|
||||
Given I shut down postgres2
|
||||
Then "sync" key in DCS has sync_standby=postgres1 after 5 seconds
|
||||
When I start postgres2
|
||||
And I shut down postgres1
|
||||
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
|
||||
When I issue a GET request to http://127.0.0.1:8010/sync
|
||||
Then I receive a response code 200
|
||||
When I issue a GET request to http://127.0.0.1:8009/async
|
||||
Then I receive a response code 200
|
||||
|
||||
Scenario: check the basic failover in synchronous mode
|
||||
When I kill postgres0
|
||||
Then postgres2 role is the primary after 22 seconds
|
||||
When I issue a PATCH request to http://127.0.0.1:8009/config with {"synchronous_mode": null, "master_start_timeout": 0}
|
||||
Given I run patronictl.py pause batman
|
||||
Then I receive a response returncode 0
|
||||
When I sleep for 2 seconds
|
||||
And I shut down postgres0
|
||||
And I run patronictl.py resume batman
|
||||
Then I receive a response returncode 0
|
||||
And postgres2 role is the primary after 24 seconds
|
||||
And Response on GET http://127.0.0.1:8010/history contains recovery after 10 seconds
|
||||
When I issue a PATCH request to http://127.0.0.1:8010/config with {"synchronous_mode": null, "master_start_timeout": 0}
|
||||
Then I receive a response code 200
|
||||
When I add the table bar to postgres2
|
||||
Then table bar is present on postgres1 after 20 seconds
|
||||
And Response on GET http://127.0.0.1:8010/config contains master_start_timeout after 10 seconds
|
||||
|
||||
Scenario: check immediate failover when master_start_timeout=0
|
||||
Given I kill postmaster on postgres2
|
||||
@@ -34,7 +49,8 @@ Feature: basic replication
|
||||
And postgres1 role is the primary after 10 seconds
|
||||
|
||||
Scenario: check rejoin of the former master with pg_rewind
|
||||
Given I start postgres0
|
||||
Given I add the table splitbrain to postgres0
|
||||
And I start postgres0
|
||||
Then postgres0 role is the secondary after 20 seconds
|
||||
When I add the table buz to postgres1
|
||||
Then table buz is present on postgres0 after 20 seconds
|
||||
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env python
|
||||
import os
|
||||
import psycopg2
|
||||
import sys
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not (len(sys.argv) >= 3 and sys.argv[3] == "master"):
|
||||
sys.exit(1)
|
||||
|
||||
os.environ['PGPASSWORD'] = 'zalando'
|
||||
connection = psycopg2.connect(host='127.0.0.1', port=sys.argv[1], user='postgres')
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT slot_name FROM pg_replication_slots WHERE slot_type = 'logical'")
|
||||
|
||||
with open("data/postgres0/label", "w") as label:
|
||||
label.write(next(iter(cursor.fetchone()), ""))
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import sys
|
||||
with open("data/{0}/{0}_cb.log".format(sys.argv[1]), "a+") as log:
|
||||
log.write(" ".join(sys.argv[-3:]) + "\n")
|
||||
@@ -0,0 +1,17 @@
|
||||
Feature: custom bootstrap
|
||||
We should check that patroni can bootstrap a new cluster from a backup
|
||||
|
||||
Scenario: clone existing cluster using pg_basebackup
|
||||
Given I start postgres0
|
||||
Then postgres0 is a leader after 10 seconds
|
||||
When I add the table foo to postgres0
|
||||
And I start postgres1 in a cluster batman1 as a clone of postgres0
|
||||
Then postgres1 is a leader of batman1 after 10 seconds
|
||||
Then table foo is present on postgres1 after 10 seconds
|
||||
|
||||
Scenario: make a backup and do a restore into a new cluster
|
||||
Given I add the table bar to postgres1
|
||||
And I do a backup of postgres1
|
||||
When I start postgres2 in a cluster batman2 from backup
|
||||
Then postgres2 is a leader of batman2 after 30 seconds
|
||||
And table bar is present on postgres2 after 10 seconds
|
||||
+426
-69
@@ -1,14 +1,15 @@
|
||||
import abc
|
||||
import consul
|
||||
import etcd
|
||||
import kazoo.client
|
||||
import kazoo.exceptions
|
||||
import datetime
|
||||
import os
|
||||
import psycopg2
|
||||
import json
|
||||
import shutil
|
||||
import signal
|
||||
import six
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import yaml
|
||||
|
||||
@@ -74,18 +75,29 @@ class AbstractController(object):
|
||||
if self._log:
|
||||
self._log.close()
|
||||
|
||||
def cancel_background(self):
|
||||
pass
|
||||
|
||||
|
||||
class PatroniController(AbstractController):
|
||||
__PORT = 5440
|
||||
__PORT = 5360
|
||||
PATRONI_CONFIG = '{}.yml'
|
||||
""" starts and stops individual patronis"""
|
||||
|
||||
def __init__(self, context, name, work_directory, output_dir, tags=None):
|
||||
def __init__(self, context, name, work_directory, output_dir, custom_config=None):
|
||||
super(PatroniController, self).__init__(context, 'patroni_' + name, work_directory, output_dir)
|
||||
PatroniController.__PORT += 1
|
||||
self._data_dir = os.path.join(work_directory, 'data', name)
|
||||
self._connstring = None
|
||||
self._config = self._make_patroni_test_config(name, tags)
|
||||
if custom_config and 'watchdog' in custom_config:
|
||||
self.watchdog = WatchdogMonitor(name, work_directory, output_dir)
|
||||
custom_config['watchdog'] = {'driver': 'testing', 'device': self.watchdog.fifo_path, 'mode': 'required'}
|
||||
else:
|
||||
self.watchdog = None
|
||||
|
||||
self._scope = (custom_config or {}).get('scope', 'batman')
|
||||
self._config = self._make_patroni_test_config(name, custom_config)
|
||||
self._closables = []
|
||||
|
||||
self._conn = None
|
||||
self._curs = None
|
||||
@@ -94,62 +106,98 @@ class PatroniController(AbstractController):
|
||||
with open(os.path.join(self._data_dir, 'label'), 'w') as f:
|
||||
f.write(content)
|
||||
|
||||
def read_label(self):
|
||||
def read_label(self, label):
|
||||
try:
|
||||
with open(os.path.join(self._data_dir, 'label'), 'r') as f:
|
||||
with open(os.path.join(self._data_dir, label), 'r') as f:
|
||||
return f.read().strip()
|
||||
except IOError:
|
||||
return None
|
||||
|
||||
def add_tag_to_config(self, tag, value):
|
||||
@staticmethod
|
||||
def recursive_update(dst, src):
|
||||
for k, v in src.items():
|
||||
if k in dst and isinstance(dst[k], dict):
|
||||
PatroniController.recursive_update(dst[k], v)
|
||||
else:
|
||||
dst[k] = v
|
||||
|
||||
def update_config(self, custom_config):
|
||||
with open(self._config) as r:
|
||||
config = yaml.safe_load(r)
|
||||
config['tags']['tag'] = value
|
||||
self.recursive_update(config, custom_config)
|
||||
with open(self._config, 'w') as w:
|
||||
yaml.safe_dump(config, w, default_flow_style=False)
|
||||
self._scope = config.get('scope', 'batman')
|
||||
|
||||
def add_tag_to_config(self, tag, value):
|
||||
self.update_config({'tags': {tag: value}})
|
||||
|
||||
def _start(self):
|
||||
return subprocess.Popen(['coverage', 'run', '--source=patroni', '-p', 'patroni.py', self._config],
|
||||
if self.watchdog:
|
||||
self.watchdog.start()
|
||||
if isinstance(self._context.dcs_ctl, KubernetesController):
|
||||
self._context.dcs_ctl.create_pod(self._name[8:], self._scope)
|
||||
os.environ['PATRONI_KUBERNETES_POD_IP'] = '10.0.0.' + self._name[-1]
|
||||
return subprocess.Popen([sys.executable, '-m', 'coverage', 'run',
|
||||
'--source=patroni', '-p', 'patroni.py', self._config],
|
||||
stdout=self._log, stderr=subprocess.STDOUT, cwd=self._work_directory)
|
||||
|
||||
def stop(self, kill=False, timeout=15, postgres=False):
|
||||
if postgres:
|
||||
return subprocess.call(['pg_ctl', '-D', self._data_dir, 'stop', '-mi', '-w'])
|
||||
super(PatroniController, self).stop(kill, timeout)
|
||||
if isinstance(self._context.dcs_ctl, KubernetesController):
|
||||
self._context.dcs_ctl.delete_pod(self._name[8:])
|
||||
if self.watchdog:
|
||||
self.watchdog.stop()
|
||||
|
||||
def _is_accessible(self):
|
||||
return self.query("SELECT 1", fail_ok=True) is not None
|
||||
cursor = self.query("SELECT 1", fail_ok=True)
|
||||
if cursor is not None:
|
||||
cursor.execute("SET synchronous_commit TO 'local'")
|
||||
return True
|
||||
|
||||
def _make_patroni_test_config(self, name, tags):
|
||||
def _make_patroni_test_config(self, name, custom_config):
|
||||
patroni_config_name = self.PATRONI_CONFIG.format(name)
|
||||
patroni_config_path = os.path.join(self._output_dir, patroni_config_name)
|
||||
|
||||
with open(patroni_config_name) as f:
|
||||
config = yaml.safe_load(f)
|
||||
config.pop('etcd')
|
||||
config.pop('etcd', None)
|
||||
|
||||
host = config['postgresql']['listen'].split(':')[0]
|
||||
|
||||
config['postgresql']['listen'] = config['postgresql']['connect_address'] = '{0}:{1}'.format(host, self.__PORT)
|
||||
|
||||
config['name'] = name
|
||||
config['postgresql']['data_dir'] = self._data_dir
|
||||
config['postgresql']['use_unix_socket'] = os.name != 'nt' # windows doesn't yet support unix-domain sockets
|
||||
config['postgresql']['pgpass'] = os.path.join(tempfile.gettempdir(), 'pgpass_' + name)
|
||||
config['postgresql']['parameters'].update({
|
||||
'logging_collector': 'on', 'log_destination': 'csvlog', 'log_directory': self._output_dir,
|
||||
'log_filename': name + '.log', 'log_statement': 'all', 'log_min_messages': 'debug1',
|
||||
'unix_socket_directories': self._data_dir})
|
||||
|
||||
if 'bootstrap' in config:
|
||||
config['bootstrap']['post_bootstrap'] = 'psql -w -c "SELECT 1"'
|
||||
if 'initdb' in config['bootstrap']:
|
||||
config['bootstrap']['initdb'].extend([{'auth': 'md5'}, {'auth-host': 'md5'}])
|
||||
|
||||
if custom_config is not None:
|
||||
self.recursive_update(config, custom_config)
|
||||
|
||||
if config['postgresql'].get('callbacks', {}).get('on_role_change'):
|
||||
config['postgresql']['callbacks']['on_role_change'] += ' ' + str(self.__PORT)
|
||||
|
||||
with open(patroni_config_path, 'w') as f:
|
||||
yaml.safe_dump(config, f, default_flow_style=False)
|
||||
|
||||
user = config['postgresql'].get('authentication', config['postgresql']).get('superuser', {})
|
||||
self._connkwargs = {k: user[n] for n, k in [('username', 'user'), ('password', 'password')] if n in user}
|
||||
self._connkwargs.update({'host': host, 'port': self.__PORT, 'database': 'postgres'})
|
||||
|
||||
config['name'] = name
|
||||
config['postgresql']['data_dir'] = self._data_dir
|
||||
config['postgresql']['parameters'].update({
|
||||
'logging_collector': 'on', 'log_destination': 'csvlog', 'log_directory': self._output_dir,
|
||||
'log_filename': name + '.log', 'log_statement': 'all', 'log_min_messages': 'debug1'})
|
||||
|
||||
if 'bootstrap' in config and 'initdb' in config['bootstrap']:
|
||||
config['bootstrap']['initdb'].extend([{'auth': 'md5'}, {'auth-host': 'md5'}])
|
||||
|
||||
if tags:
|
||||
config['tags'] = tags
|
||||
|
||||
with open(patroni_config_path, 'w') as f:
|
||||
yaml.safe_dump(config, f, default_flow_style=False)
|
||||
self._replication = config['postgresql'].get('authentication', config['postgresql']).get('replication', {})
|
||||
self._replication.update({'host': host, 'port': self.__PORT, 'database': 'postgres'})
|
||||
|
||||
return patroni_config_path
|
||||
|
||||
@@ -185,10 +233,66 @@ class PatroniController(AbstractController):
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
def get_watchdog(self):
|
||||
return self.watchdog
|
||||
|
||||
def _get_pid(self):
|
||||
try:
|
||||
pidfile = os.path.join(self._data_dir, 'postmaster.pid')
|
||||
if not os.path.exists(pidfile):
|
||||
return None
|
||||
return int(open(pidfile).readline().strip())
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def patroni_hang(self, timeout):
|
||||
hang = ProcessHang(self._handle.pid, timeout)
|
||||
self._closables.append(hang)
|
||||
hang.start()
|
||||
|
||||
def cancel_background(self):
|
||||
for obj in self._closables:
|
||||
obj.close()
|
||||
self._closables = []
|
||||
|
||||
@property
|
||||
def backup_source(self):
|
||||
return 'postgres://{username}:{password}@{host}:{port}/{database}'.format(**self._replication)
|
||||
|
||||
def backup(self, dest=os.path.join('data', 'basebackup')):
|
||||
subprocess.call(PatroniPoolController.BACKUP_SCRIPT + ['--walmethod=none',
|
||||
'--datadir=' + os.path.join(self._work_directory, dest),
|
||||
'--dbname=' + self.backup_source])
|
||||
|
||||
|
||||
class ProcessHang(object):
|
||||
|
||||
"""A background thread implementing a cancelable process hang via SIGSTOP."""
|
||||
|
||||
def __init__(self, pid, timeout):
|
||||
self._cancelled = threading.Event()
|
||||
self._thread = threading.Thread(target=self.run)
|
||||
self.pid = pid
|
||||
self.timeout = timeout
|
||||
|
||||
def start(self):
|
||||
self._thread.start()
|
||||
|
||||
def run(self):
|
||||
os.kill(self.pid, signal.SIGSTOP)
|
||||
try:
|
||||
self._cancelled.wait(self.timeout)
|
||||
finally:
|
||||
os.kill(self.pid, signal.SIGCONT)
|
||||
|
||||
def close(self):
|
||||
self._cancelled.set()
|
||||
self._thread.join()
|
||||
|
||||
|
||||
class AbstractDcsController(AbstractController):
|
||||
|
||||
_CLUSTER_NODE = '/service/batman'
|
||||
_CLUSTER_NODE = '/service/{0}'
|
||||
|
||||
def __init__(self, context, mktemp=True):
|
||||
work_directory = mktemp and tempfile.mkdtemp() or None
|
||||
@@ -203,17 +307,13 @@ class AbstractDcsController(AbstractController):
|
||||
if self._work_directory:
|
||||
shutil.rmtree(self._work_directory)
|
||||
|
||||
def path(self, key=None):
|
||||
return self._CLUSTER_NODE + (key and '/' + key or '')
|
||||
def path(self, key=None, scope='batman'):
|
||||
return self._CLUSTER_NODE.format(scope) + (key and '/' + key or '')
|
||||
|
||||
@abc.abstractmethod
|
||||
def query(self, key):
|
||||
def query(self, key, scope='batman'):
|
||||
""" query for a value of a given key """
|
||||
|
||||
@abc.abstractmethod
|
||||
def set(self, key, value):
|
||||
""" set a value to a given key """
|
||||
|
||||
@abc.abstractmethod
|
||||
def cleanup_service_tree(self):
|
||||
""" clean all contents stored in the tree used for the tests """
|
||||
@@ -235,19 +335,23 @@ class ConsulController(AbstractDcsController):
|
||||
def __init__(self, context):
|
||||
super(ConsulController, self).__init__(context)
|
||||
os.environ['PATRONI_CONSUL_HOST'] = 'localhost:8500'
|
||||
os.environ['PATRONI_CONSUL_REGISTER_SERVICE'] = 'on'
|
||||
self._config_file = None
|
||||
|
||||
import consul
|
||||
self._client = consul.Consul()
|
||||
|
||||
def _start(self):
|
||||
config_file = self._work_directory + '.json'
|
||||
with open(config_file, 'wb') as f:
|
||||
self._config_file = self._work_directory + '.json'
|
||||
with open(self._config_file, 'wb') as f:
|
||||
f.write(b'{"session_ttl_min":"5s","server":true,"bootstrap":true,"advertise_addr":"127.0.0.1"}')
|
||||
return subprocess.Popen(['consul', 'agent', '-config-file', config_file, '-data-dir', self._work_directory],
|
||||
stdout=self._log, stderr=subprocess.STDOUT)
|
||||
return subprocess.Popen(['consul', 'agent', '-config-file', self._config_file, '-data-dir',
|
||||
self._work_directory], stdout=self._log, stderr=subprocess.STDOUT)
|
||||
|
||||
def stop(self, kill=False, timeout=15):
|
||||
super(ConsulController, self).stop(kill=kill, timeout=timeout)
|
||||
if self._work_directory:
|
||||
os.unlink(self._work_directory + '.json')
|
||||
if self._config_file:
|
||||
os.unlink(self._config_file)
|
||||
|
||||
def _is_running(self):
|
||||
try:
|
||||
@@ -255,18 +359,15 @@ class ConsulController(AbstractDcsController):
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def path(self, key=None):
|
||||
return super(ConsulController, self).path(key)[1:]
|
||||
def path(self, key=None, scope='batman'):
|
||||
return super(ConsulController, self).path(key, scope)[1:]
|
||||
|
||||
def query(self, key):
|
||||
_, value = self._client.kv.get(self.path(key))
|
||||
def query(self, key, scope='batman'):
|
||||
_, value = self._client.kv.get(self.path(key, scope))
|
||||
return value and value['Value'].decode('utf-8')
|
||||
|
||||
def set(self, key, value):
|
||||
self._client.kv.put(self.path(key), value)
|
||||
|
||||
def cleanup_service_tree(self):
|
||||
self._client.kv.delete(self.path(), recurse=True)
|
||||
self._client.kv.delete(self.path(scope=''), recurse=True)
|
||||
|
||||
def start(self, max_wait_limit=15):
|
||||
super(ConsulController, self).start(max_wait_limit)
|
||||
@@ -279,24 +380,25 @@ class EtcdController(AbstractDcsController):
|
||||
def __init__(self, context):
|
||||
super(EtcdController, self).__init__(context)
|
||||
os.environ['PATRONI_ETCD_HOST'] = 'localhost:2379'
|
||||
|
||||
import etcd
|
||||
self._client = etcd.Client(port=2379)
|
||||
|
||||
def _start(self):
|
||||
return subprocess.Popen(["etcd", "--debug", "--data-dir", self._work_directory],
|
||||
stdout=self._log, stderr=subprocess.STDOUT)
|
||||
|
||||
def query(self, key):
|
||||
def query(self, key, scope='batman'):
|
||||
import etcd
|
||||
try:
|
||||
return self._client.get(self.path(key)).value
|
||||
return self._client.get(self.path(key, scope)).value
|
||||
except etcd.EtcdKeyNotFound:
|
||||
return None
|
||||
|
||||
def set(self, key, value):
|
||||
self._client.set(self.path(key), value)
|
||||
|
||||
def cleanup_service_tree(self):
|
||||
import etcd
|
||||
try:
|
||||
self._client.delete(self.path(), recursive=True)
|
||||
self._client.delete(self.path(scope=''), recursive=True)
|
||||
except (etcd.EtcdKeyNotFound, etcd.EtcdConnectionFailed):
|
||||
return
|
||||
except Exception as e:
|
||||
@@ -310,6 +412,77 @@ class EtcdController(AbstractDcsController):
|
||||
return False
|
||||
|
||||
|
||||
class KubernetesController(AbstractDcsController):
|
||||
|
||||
def __init__(self, context):
|
||||
super(KubernetesController, self).__init__(context)
|
||||
self._namespace = 'default'
|
||||
self._labels = {"application": "patroni"}
|
||||
self._label_selector = ','.join('{0}={1}'.format(k, v) for k, v in self._labels.items())
|
||||
os.environ['PATRONI_KUBERNETES_LABELS'] = json.dumps(self._labels)
|
||||
os.environ['PATRONI_KUBERNETES_USE_ENDPOINTS'] = 'true'
|
||||
|
||||
from kubernetes import client as k8s_client, config as k8s_config
|
||||
k8s_config.load_kube_config(context='local')
|
||||
self._client = k8s_client
|
||||
self._api = self._client.CoreV1Api()
|
||||
|
||||
def _start(self):
|
||||
pass
|
||||
|
||||
def create_pod(self, name, scope):
|
||||
labels = self._labels.copy()
|
||||
labels['cluster-name'] = scope
|
||||
metadata = self._client.V1ObjectMeta(namespace=self._namespace, name=name, labels=labels)
|
||||
spec = self._client.V1PodSpec(containers=[self._client.V1Container(name=name, image='empty')])
|
||||
body = self._client.V1Pod(metadata=metadata, spec=spec)
|
||||
self._api.create_namespaced_pod(self._namespace, body)
|
||||
|
||||
def delete_pod(self, name):
|
||||
try:
|
||||
self._api.delete_namespaced_pod(name, self._namespace, body=self._client.V1DeleteOptions())
|
||||
except Exception:
|
||||
pass
|
||||
while True:
|
||||
try:
|
||||
self._api.read_namespaced_pod(name, self._namespace)
|
||||
except Exception:
|
||||
break
|
||||
|
||||
def query(self, key, scope='batman'):
|
||||
if key.startswith('members/'):
|
||||
pod = self._api.read_namespaced_pod(key[8:], self._namespace)
|
||||
return (pod.metadata.annotations or {}).get('status', '')
|
||||
else:
|
||||
try:
|
||||
ep = scope + {'leader': '', 'history': '-config', 'initialize': '-config'}.get(key, '-' + key)
|
||||
e = self._api.read_namespaced_endpoints(ep, self._namespace)
|
||||
if key != 'sync':
|
||||
return e.metadata.annotations[key]
|
||||
else:
|
||||
return json.dumps(e.metadata.annotations)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def cleanup_service_tree(self):
|
||||
try:
|
||||
self._api.delete_collection_namespaced_pod(self._namespace, label_selector=self._label_selector)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self._api.delete_collection_namespaced_endpoints(self._namespace, label_selector=self._label_selector)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
while True:
|
||||
result = self._api.list_namespaced_pod(self._namespace, label_selector=self._label_selector)
|
||||
if len(result.items) < 1:
|
||||
break
|
||||
|
||||
def _is_running(self):
|
||||
return True
|
||||
|
||||
|
||||
class ZooKeeperController(AbstractDcsController):
|
||||
|
||||
""" handles all zookeeper related tasks, used for the tests setup and cleanup """
|
||||
@@ -318,23 +491,24 @@ class ZooKeeperController(AbstractDcsController):
|
||||
super(ZooKeeperController, self).__init__(context, False)
|
||||
if export_env:
|
||||
os.environ['PATRONI_ZOOKEEPER_HOSTS'] = "'localhost:2181'"
|
||||
|
||||
import kazoo.client
|
||||
self._client = kazoo.client.KazooClient()
|
||||
|
||||
def _start(self):
|
||||
pass # TODO: implement later
|
||||
|
||||
def query(self, key):
|
||||
def query(self, key, scope='batman'):
|
||||
import kazoo.exceptions
|
||||
try:
|
||||
return self._client.get(self.path(key))[0].decode('utf-8')
|
||||
return self._client.get(self.path(key, scope))[0].decode('utf-8')
|
||||
except kazoo.exceptions.NoNodeError:
|
||||
return None
|
||||
|
||||
def set(self, key, value):
|
||||
self._client.set(self.path(key), value.encode('utf-8'))
|
||||
|
||||
def cleanup_service_tree(self):
|
||||
import kazoo.exceptions
|
||||
try:
|
||||
self._client.delete(self.path(), recursive=True)
|
||||
self._client.delete(self.path(scope=''), recursive=True)
|
||||
except (kazoo.exceptions.NoNodeError):
|
||||
return
|
||||
except Exception as e:
|
||||
@@ -359,6 +533,9 @@ class ExhibitorController(ZooKeeperController):
|
||||
|
||||
class PatroniPoolController(object):
|
||||
|
||||
BACKUP_SCRIPT = [sys.executable, 'features/backup_create.py']
|
||||
ARCHIVE_RESTORE_SCRIPT = ' '.join((sys.executable, os.path.abspath('features/archive-restore.py')))
|
||||
|
||||
def __init__(self, context):
|
||||
self._context = context
|
||||
self._dcs = None
|
||||
@@ -383,13 +560,15 @@ class PatroniPoolController(object):
|
||||
def output_dir(self):
|
||||
return self._output_dir
|
||||
|
||||
def start(self, name, max_wait_limit=20, tags=None):
|
||||
def start(self, name, max_wait_limit=20, custom_config=None):
|
||||
if name not in self._processes:
|
||||
self._processes[name] = PatroniController(self._context, name, self.patroni_path, self._output_dir, tags)
|
||||
self._processes[name] = PatroniController(self._context, name, self.patroni_path,
|
||||
self._output_dir, custom_config)
|
||||
self._processes[name].start(max_wait_limit)
|
||||
|
||||
def __getattr__(self, func):
|
||||
if func not in ['stop', 'query', 'write_label', 'read_label', 'check_role_has_changed_to', 'add_tag_to_config']:
|
||||
if func not in ['stop', 'query', 'write_label', 'read_label', 'check_role_has_changed_to',
|
||||
'add_tag_to_config', 'get_watchdog', 'patroni_hang', 'backup']:
|
||||
raise AttributeError("PatroniPoolController instance has no attribute '{0}'".format(func))
|
||||
|
||||
def wrapper(name, *args, **kwargs):
|
||||
@@ -398,16 +577,75 @@ class PatroniPoolController(object):
|
||||
|
||||
def stop_all(self):
|
||||
for ctl in self._processes.values():
|
||||
ctl.cancel_background()
|
||||
ctl.stop()
|
||||
self._processes.clear()
|
||||
|
||||
def create_and_set_output_directory(self, feature_name):
|
||||
feature_dir = os.path.join(self.patroni_path, 'features/output', feature_name.replace(' ', '_'))
|
||||
feature_dir = os.path.join(self.patroni_path, 'features', 'output', feature_name.replace(' ', '_'))
|
||||
if os.path.exists(feature_dir):
|
||||
shutil.rmtree(feature_dir)
|
||||
os.makedirs(feature_dir)
|
||||
self._output_dir = feature_dir
|
||||
|
||||
def clone(self, from_name, cluster_name, to_name):
|
||||
f = self._processes[from_name]
|
||||
custom_config = {
|
||||
'scope': cluster_name,
|
||||
'bootstrap': {
|
||||
'method': 'pg_basebackup',
|
||||
'pg_basebackup': {
|
||||
'command': " ".join(self.BACKUP_SCRIPT) + ' --walmethod=stream --dbname=' + f.backup_source
|
||||
},
|
||||
'dcs': {
|
||||
'postgresql': {
|
||||
'parameters': {
|
||||
'max_connections': 101
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'postgresql': {
|
||||
'parameters': {
|
||||
'archive_mode': 'on',
|
||||
'archive_command': (self.ARCHIVE_RESTORE_SCRIPT + ' --mode archive ' +
|
||||
'--dirname {} --filename %f --pathname %p').format(
|
||||
os.path.join(self.patroni_path, 'data', 'wal_archive'))
|
||||
},
|
||||
'authentication': {
|
||||
'superuser': {'password': 'zalando1'},
|
||||
'replication': {'password': 'rep-pass1'}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.start(to_name, custom_config=custom_config)
|
||||
|
||||
def bootstrap_from_backup(self, name, cluster_name):
|
||||
custom_config = {
|
||||
'scope': cluster_name,
|
||||
'bootstrap': {
|
||||
'method': 'backup_restore',
|
||||
'backup_restore': {
|
||||
'command': (sys.executable + ' features/backup_restore.py --sourcedir=' +
|
||||
os.path.join(self.patroni_path, 'data', 'basebackup')),
|
||||
'recovery_conf': {
|
||||
'recovery_target_action': 'promote',
|
||||
'recovery_target_timeline': 'latest',
|
||||
'restore_command': (self.ARCHIVE_RESTORE_SCRIPT + ' --mode restore ' +
|
||||
'--dirname {} --filename %f --pathname %p').format(
|
||||
os.path.join(self.patroni_path, 'data', 'wal_archive'))
|
||||
}
|
||||
}
|
||||
},
|
||||
'postgresql': {
|
||||
'authentication': {
|
||||
'superuser': {'password': 'zalando2'},
|
||||
'replication': {'password': 'rep-pass2'}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.start(name, custom_config=custom_config)
|
||||
|
||||
@property
|
||||
def dcs(self):
|
||||
if self._dcs is None:
|
||||
@@ -416,8 +654,125 @@ class PatroniPoolController(object):
|
||||
return self._dcs
|
||||
|
||||
|
||||
class WatchdogMonitor(object):
|
||||
"""Testing harness for emulating a watchdog device as a named pipe. Because we can't easily emulate ioctl's we
|
||||
require a custom driver on Patroni side. The device takes no action, only notes if it was pinged and/or triggered.
|
||||
"""
|
||||
def __init__(self, name, work_directory, output_dir):
|
||||
self.fifo_path = os.path.join(work_directory, 'data', 'watchdog.{0}.fifo'.format(name))
|
||||
self.fifo_file = None
|
||||
self._stop_requested = False # Relying on bool setting being atomic
|
||||
self._thread = None
|
||||
self.last_ping = None
|
||||
self.was_pinged = False
|
||||
self.was_closed = False
|
||||
self._was_triggered = False
|
||||
self.timeout = 60
|
||||
self._log_file = open(os.path.join(output_dir, 'watchdog.{0}.log'.format(name)), 'w')
|
||||
self._log("watchdog {0} initialized".format(name))
|
||||
|
||||
def _log(self, msg):
|
||||
tstamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")
|
||||
self._log_file.write("{0}: {1}\n".format(tstamp, msg))
|
||||
|
||||
def start(self):
|
||||
assert self._thread is None
|
||||
self._stop_requested = False
|
||||
self._log("starting fifo {0}".format(self.fifo_path))
|
||||
fifo_dir = os.path.dirname(self.fifo_path)
|
||||
if os.path.exists(self.fifo_path):
|
||||
os.unlink(self.fifo_path)
|
||||
elif not os.path.exists(fifo_dir):
|
||||
os.mkdir(fifo_dir)
|
||||
os.mkfifo(self.fifo_path)
|
||||
self.last_ping = time.time()
|
||||
|
||||
self._thread = threading.Thread(target=self.run)
|
||||
self._thread.start()
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
while not self._stop_requested:
|
||||
self._log("opening")
|
||||
self.fifo_file = os.open(self.fifo_path, os.O_RDONLY)
|
||||
try:
|
||||
self._log("Fifo {0} connected".format(self.fifo_path))
|
||||
self.was_closed = False
|
||||
while not self._stop_requested:
|
||||
c = os.read(self.fifo_file, 1)
|
||||
|
||||
if c == b'X':
|
||||
self._log("Stop requested")
|
||||
return
|
||||
elif c == b'':
|
||||
self._log("Pipe closed")
|
||||
break
|
||||
elif c == b'C':
|
||||
command = b''
|
||||
c = os.read(self.fifo_file, 1)
|
||||
while c != b'\n' and c != b'':
|
||||
command += c
|
||||
c = os.read(self.fifo_file, 1)
|
||||
command = command.decode('utf8')
|
||||
|
||||
if command.startswith('timeout='):
|
||||
self.timeout = int(command.split('=')[1])
|
||||
self._log("timeout={0}".format(self.timeout))
|
||||
elif c in [b'V', b'1']:
|
||||
cur_time = time.time()
|
||||
if cur_time - self.last_ping > self.timeout:
|
||||
self._log("Triggered")
|
||||
self._was_triggered = True
|
||||
if c == b'V':
|
||||
self._log("magic close")
|
||||
self.was_closed = True
|
||||
elif c == b'1':
|
||||
self.was_pinged = True
|
||||
self._log("ping after {0} seconds".format(cur_time - (self.last_ping or cur_time)))
|
||||
self.last_ping = cur_time
|
||||
else:
|
||||
self._log('Unknown command {0} received from fifo'.format(c))
|
||||
finally:
|
||||
self.was_closed = True
|
||||
self._log("closing")
|
||||
os.close(self.fifo_file)
|
||||
except Exception as e:
|
||||
self._log("Error {0}".format(e))
|
||||
finally:
|
||||
self._log("stopping")
|
||||
self._log_file.flush()
|
||||
if os.path.exists(self.fifo_path):
|
||||
os.unlink(self.fifo_path)
|
||||
|
||||
def stop(self):
|
||||
self._log("Monitor stop")
|
||||
self._stop_requested = True
|
||||
try:
|
||||
if os.path.exists(self.fifo_path):
|
||||
fd = os.open(self.fifo_path, os.O_WRONLY)
|
||||
os.write(fd, b'X')
|
||||
os.close(fd)
|
||||
except Exception as e:
|
||||
self._log("err while closing: {0}".format(str(e)))
|
||||
if self._thread:
|
||||
self._thread.join()
|
||||
self._thread = None
|
||||
|
||||
def reset(self):
|
||||
self._log("reset")
|
||||
self.was_pinged = self.was_closed = self._was_triggered = False
|
||||
|
||||
@property
|
||||
def was_triggered(self):
|
||||
delta = time.time() - self.last_ping
|
||||
triggered = self._was_triggered or not self.was_closed and delta > self.timeout
|
||||
self._log("triggered={0}, {1}s left".format(triggered, self.timeout - delta))
|
||||
return triggered
|
||||
|
||||
|
||||
# actions to execute on start/stop of the tests and before running invidual features
|
||||
def before_all(context):
|
||||
os.environ.update({'PATRONI_RESTAPI_USERNAME': 'username', 'PATRONI_RESTAPI_PASSWORD': 'password'})
|
||||
context.ci = 'TRAVIS_BUILD_NUMBER' in os.environ or 'BUILD_NUMBER' in os.environ
|
||||
context.timeout_multiplier = 2 if context.ci else 1
|
||||
context.pctl = PatroniPoolController(context)
|
||||
@@ -432,8 +787,8 @@ def before_all(context):
|
||||
|
||||
def after_all(context):
|
||||
context.dcs_ctl.stop()
|
||||
subprocess.call(['coverage', 'combine'])
|
||||
subprocess.call(['coverage', 'report'])
|
||||
subprocess.call([sys.executable, '-m', 'coverage', 'combine'])
|
||||
subprocess.call([sys.executable, '-m', 'coverage', 'report'])
|
||||
|
||||
|
||||
def before_feature(context, feature):
|
||||
@@ -446,3 +801,5 @@ def after_feature(context, feature):
|
||||
context.pctl.stop_all()
|
||||
shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data'))
|
||||
context.dcs_ctl.cleanup_service_tree()
|
||||
if feature.status == 'failed':
|
||||
shutil.copytree(context.pctl.output_dir, context.pctl.output_dir + '_failed')
|
||||
|
||||
@@ -8,42 +8,57 @@ Scenario: check API requests on a stand-alone server
|
||||
Then I receive a response code 200
|
||||
And I receive a response state running
|
||||
And I receive a response role master
|
||||
When I issue a GET request to http://127.0.0.1:8008/standby_leader
|
||||
Then I receive a response code 503
|
||||
When I issue a GET request to http://127.0.0.1:8008/health
|
||||
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 run patronictl.py reinit batman postgres0 --force
|
||||
Then I receive a response returncode 0
|
||||
And I receive a response output "Failed: reinitialize for member postgres0, status code=503, (I am the leader, can not reinitialize)"
|
||||
When I run patronictl.py failover batman --master postgres0 --force
|
||||
When I run patronictl.py switchover batman --master postgres0 --force
|
||||
Then I receive a response returncode 1
|
||||
And I receive a response output "Error: No candidates found to failover to"
|
||||
When I issue a POST request to http://127.0.0.1:8008/failover with {"leader": "postgres0"}
|
||||
Then I receive a response code 500
|
||||
And I receive a response text failover is not possible: cluster does not have members except leader
|
||||
And I receive a response output "Error: No candidates found to switchover to"
|
||||
When I issue a POST request to http://127.0.0.1:8008/switchover with {"leader": "postgres0"}
|
||||
Then I receive a response code 412
|
||||
And I receive a response text switchover is not possible: cluster does not have members except leader
|
||||
When I issue an empty POST request to http://127.0.0.1:8008/failover
|
||||
Then I receive a response code 400
|
||||
When I issue a POST request to http://127.0.0.1:8008/failover with {"foo": "bar"}
|
||||
Then I receive a response code 400
|
||||
And I receive a response text "No values given for required parameters leader and candidate"
|
||||
And I receive a response text "Failover could be performed only to a specific candidate"
|
||||
|
||||
Scenario: check local configuration reload
|
||||
Given I issue an empty POST request to http://127.0.0.1:8008/reload
|
||||
Then I receive a response code 200
|
||||
And I receive a response text nothing changed
|
||||
When I add tag new_tag new_value to postgres0 config
|
||||
Given I add tag new_tag new_value to postgres0 config
|
||||
And I issue an empty POST request to http://127.0.0.1:8008/reload
|
||||
Then I receive a response code 202
|
||||
|
||||
Scenario: check dynamic configuration change via DCS
|
||||
Given I issue a PATCH request to http://127.0.0.1:8008/config with {"ttl": 10, "loop_wait": 2, "postgresql": {"parameters": {"max_connections": 101}}}
|
||||
Then I receive a response code 200
|
||||
And I receive a response loop_wait 2
|
||||
Given I run patronictl.py edit-config -s 'ttl=10' -s 'loop_wait=2' -p 'max_connections=101' --force batman
|
||||
Then I receive a response returncode 0
|
||||
And I receive a response output "+loop_wait: 2"
|
||||
And Response on GET http://127.0.0.1:8008/patroni contains pending_restart after 11 seconds
|
||||
When I issue a GET request to http://127.0.0.1:8008/config
|
||||
Then I receive a response code 200
|
||||
And I receive a response loop_wait 2
|
||||
When I issue a GET request to http://127.0.0.1:8008/patroni
|
||||
Then I receive a response code 200
|
||||
And I receive a response tags {'tag': 'new_value'}
|
||||
And I receive a response tags {'new_tag': 'new_value'}
|
||||
And I sleep for 4 seconds
|
||||
|
||||
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"}}}
|
||||
Then I receive a response code 200
|
||||
And Response on GET http://127.0.0.1:8008/patroni contains pending_restart after 5 seconds
|
||||
Given I issue a scheduled restart at http://127.0.0.1:8008 in 3 seconds with {"role": "replica"}
|
||||
Then I receive a response code 202
|
||||
And I sleep for 4 seconds
|
||||
And Response on GET http://127.0.0.1:8008/patroni contains pending_restart after 10 seconds
|
||||
Given I issue a scheduled restart at http://127.0.0.1:8008 in 3 seconds with {"restart_pending": "True"}
|
||||
Then I receive a response code 202
|
||||
And Response on GET http://127.0.0.1:8008/patroni does not contain pending_restart after 10 seconds
|
||||
And postgres0 role is the primary after 10 seconds
|
||||
|
||||
Scenario: check API requests for the primary-replica pair in the pause mode
|
||||
Given I run patronictl.py pause batman
|
||||
@@ -64,36 +79,41 @@ Scenario: check API requests for the primary-replica pair in the pause mode
|
||||
When I sleep for 10 seconds
|
||||
Then postgres1 role is the secondary after 15 seconds
|
||||
|
||||
Scenario: check the failover via the API in the pause mode
|
||||
Given I run patronictl.py failover batman --master postgres0 --candidate postgres1 --force
|
||||
Then I receive a response returncode 0
|
||||
Scenario: check the switchover via the API in the pause mode
|
||||
Given I issue a POST request to http://127.0.0.1:8008/switchover with {"leader": "postgres0", "candidate": "postgres1"}
|
||||
Then I receive a response code 200
|
||||
And postgres1 is a leader after 5 seconds
|
||||
And postgres1 role is the primary after 10 seconds
|
||||
And postgres0 role is the secondary after 10 seconds
|
||||
And replication works from postgres1 to postgres0 after 20 seconds
|
||||
And "members/postgres0" key in DCS has state=running after 10 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 failover
|
||||
Given I issue a scheduled failover from postgres1 to postgres0 in 3 seconds
|
||||
Scenario: check the scheduled switchover
|
||||
Given I issue a scheduled switchover from postgres1 to postgres0 in 3 seconds
|
||||
Then I receive a response returncode 1
|
||||
And I receive a response output "Can't schedule failover in the paused state"
|
||||
And I receive a response output "Can't schedule switchover in the paused state"
|
||||
When I run patronictl.py resume batman
|
||||
Then I receive a response returncode 0
|
||||
Given I issue a scheduled failover from postgres1 to postgres0 in 3 seconds
|
||||
Given I issue a scheduled switchover from postgres1 to postgres0 in 3 seconds
|
||||
Then I receive a response returncode 0
|
||||
And postgres0 is a leader after 20 seconds
|
||||
And postgres0 role is the primary after 10 seconds
|
||||
And postgres1 role is the secondary after 10 seconds
|
||||
And replication works from postgres0 to postgres1 after 25 seconds
|
||||
|
||||
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"}}}
|
||||
And "members/postgres1" key in DCS has state=running after 10 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
|
||||
And Response on GET http://127.0.0.1:8008/patroni contains pending_restart after 5 seconds
|
||||
Given I issue a scheduled restart at http://127.0.0.1:8008 in 3 seconds with {"role": "replica"}
|
||||
Then I receive a response code 202
|
||||
And I sleep for 4 seconds
|
||||
And Response on GET http://127.0.0.1:8008/patroni contains pending_restart after 10 seconds
|
||||
Given I issue a scheduled restart at http://127.0.0.1:8008 in 3 seconds with {"restart_pending": "True"}
|
||||
Then I receive a response code 202
|
||||
And Response on GET http://127.0.0.1:8008/patroni does not contain pending_restart after 10 seconds
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
Feature: standby cluster
|
||||
Scenario: check permanent logical slots are preserved on failover/switchover
|
||||
Given I start postgres1
|
||||
Then postgres1 is a leader after 10 seconds
|
||||
And there is a non empty initialize key in DCS after 15 seconds
|
||||
When I issue a PATCH request to http://127.0.0.1:8009/config with {"loop_wait": 2, "slots": {"pm_1": {"type": "physical"}}, "postgresql": {"parameters": {"wal_level": "logical"}}}
|
||||
Then I receive a response code 200
|
||||
And Response on GET http://127.0.0.1:8009/config contains slots after 10 seconds
|
||||
And I sleep for 3 seconds
|
||||
When I issue a PATCH request to http://127.0.0.1:8009/config with {"slots": {"test_logical": {"type": "logical", "database": "postgres", "plugin": "test_decoding"}}}
|
||||
Then I receive a response code 200
|
||||
And I do a backup of postgres1
|
||||
When I start postgres0 with callback configured
|
||||
Then "members/postgres0" key in DCS has state=running after 10 seconds
|
||||
And replication works from postgres1 to postgres0 after 15 seconds
|
||||
When I shut down postgres1
|
||||
Then postgres0 is a leader after 10 seconds
|
||||
And "members/postgres0" key in DCS has role=master after 3 seconds
|
||||
When I issue a GET request to http://127.0.0.1:8008/
|
||||
Then I receive a response code 200
|
||||
And there is a label with "test_logical" in postgres0 data directory
|
||||
|
||||
Scenario: check replication of a single table in a standby cluster
|
||||
Given 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 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/standby_leader
|
||||
Then I receive a response code 200
|
||||
And I receive a response role standby_leader
|
||||
And there is a postgres1_cb.log with "on_role_change standby_leader batman1" in postgres1 data directory
|
||||
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
|
||||
And I kill postmaster on postgres1
|
||||
Then postgres2 is replicating from postgres0 after 32 seconds
|
||||
When I issue a GET request to http://127.0.0.1:8010/master
|
||||
Then I receive a response code 503
|
||||
When I issue a GET request to http://127.0.0.1:8010/standby_leader
|
||||
Then I receive a response code 200
|
||||
And I receive a response role standby_leader
|
||||
And replication works from postgres0 to postgres2 after 15 seconds
|
||||
And there is a postgres2_cb.log with "on_start replica batman1\non_role_change standby_leader batman1" in postgres2 data directory
|
||||
@@ -11,7 +11,7 @@ def start_patroni(context, name):
|
||||
|
||||
@step('I shut down {name:w}')
|
||||
def stop_patroni(context, name):
|
||||
return context.pctl.stop(name)
|
||||
return context.pctl.stop(name, timeout=60)
|
||||
|
||||
|
||||
@step('I kill {name:w}')
|
||||
|
||||
@@ -6,13 +6,14 @@ from behave import step, then
|
||||
|
||||
@step('I configure and start {name:w} with a tag {tag_name:w} {tag_value:w}')
|
||||
def start_patroni_with_a_name_value_tag(context, name, tag_name, tag_value):
|
||||
return context.pctl.start(name, tags={tag_name: tag_value})
|
||||
return context.pctl.start(name, custom_config={'tags': {tag_name: tag_value}})
|
||||
|
||||
|
||||
@then('There is a label with "{content:w}" in {name:w} data directory')
|
||||
def check_label(context, content, name):
|
||||
label = context.pctl.read_label(name)
|
||||
assert label == content, "{0} is not equal to {1}".format(label, content)
|
||||
@then('There is a {label} with "{content}" in {name:w} data directory')
|
||||
def check_label(context, label, content, name):
|
||||
label = context.pctl.read_label(name, label)
|
||||
label = label.replace('\n', '\\n')
|
||||
assert content in label, "{0} doesn't contain {1}".format(label, content)
|
||||
|
||||
|
||||
@step('I create label with "{content:w}" in {name:w} data directory')
|
||||
@@ -33,3 +34,17 @@ def check_member(context, name, key, value, time_limit):
|
||||
pass
|
||||
time.sleep(1)
|
||||
assert False, "{0} does not have {1}={2} in dcs after {3} seconds".format(name, key, value, time_limit)
|
||||
|
||||
|
||||
@step('there is a non empty {key:w} key in DCS after {time_limit:d} seconds')
|
||||
def check_initialize(context, key, time_limit):
|
||||
time_limit *= context.timeout_multiplier
|
||||
max_time = time.time() + int(time_limit)
|
||||
while time.time() < max_time:
|
||||
try:
|
||||
if context.dcs_ctl.query(key):
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
assert False, "There is no {0} in dcs after {1} seconds".format(key, time_limit)
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import time
|
||||
|
||||
from behave import step, then
|
||||
|
||||
|
||||
@step('I start {name:w} in a cluster {cluster_name:w} as a clone of {name2:w}')
|
||||
def start_cluster_clone(context, name, cluster_name, name2):
|
||||
context.pctl.clone(name2, cluster_name, name)
|
||||
|
||||
|
||||
@step('I start {name:w} in a cluster {cluster_name:w} from backup')
|
||||
def start_cluster_from_backup(context, name, cluster_name):
|
||||
context.pctl.bootstrap_from_backup(name, cluster_name)
|
||||
|
||||
|
||||
@then('{name:w} is a leader of {cluster_name:w} after {time_limit:d} seconds')
|
||||
def is_a_leader(context, name, cluster_name, time_limit):
|
||||
time_limit *= context.timeout_multiplier
|
||||
max_time = time.time() + int(time_limit)
|
||||
while (context.dcs_ctl.query("leader", scope=cluster_name) != name):
|
||||
time.sleep(1)
|
||||
assert time.time() < max_time, "{0} is not a leader in dcs after {1} seconds".format(name, time_limit)
|
||||
|
||||
|
||||
@step('I do a backup of {name:w}')
|
||||
def do_backup(context, name):
|
||||
context.pctl.backup(name)
|
||||
@@ -1,17 +1,19 @@
|
||||
import json
|
||||
import os
|
||||
import parse
|
||||
import requests
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import yaml
|
||||
|
||||
from behave import register_type, step, then
|
||||
from dateutil import tz
|
||||
from datetime import datetime, timedelta
|
||||
from patroni.request import PatroniRequest
|
||||
|
||||
tzutc = tz.tzutc()
|
||||
request_executor = PatroniRequest({'ctl': {'auth': 'username:password'}})
|
||||
|
||||
|
||||
@parse.with_pattern(r'https?://(?:\w|\.|:|/)+')
|
||||
@@ -43,9 +45,9 @@ def sleep_for_n_seconds(context, value):
|
||||
|
||||
|
||||
def _set_response(context, response):
|
||||
context.status_code = response.status_code
|
||||
data = response.content.decode('utf-8')
|
||||
ct = response.headers.get('content-type', '')
|
||||
context.status_code = response.status
|
||||
data = response.data.decode('utf-8')
|
||||
ct = response.getheader('content-type', '')
|
||||
if ct.startswith('application/json') or\
|
||||
ct.startswith('text/yaml') or\
|
||||
ct.startswith('text/x-yaml') or\
|
||||
@@ -61,13 +63,7 @@ def _set_response(context, response):
|
||||
|
||||
@step('I issue a GET request to {url:url}')
|
||||
def do_get(context, url):
|
||||
try:
|
||||
r = requests.get(url)
|
||||
except requests.exceptions.RequestException:
|
||||
context.status_code = None
|
||||
context.response = None
|
||||
else:
|
||||
_set_response(context, r)
|
||||
do_request(context, 'GET', url, None)
|
||||
|
||||
|
||||
@step('I issue an empty POST request to {url:url}')
|
||||
@@ -77,22 +73,18 @@ def do_post_empty(context, url):
|
||||
|
||||
@step('I issue a {request_method:w} request to {url:url} with {data}')
|
||||
def do_request(context, request_method, url, data):
|
||||
data = data and json.loads(data) or {}
|
||||
data = data and json.loads(data)
|
||||
try:
|
||||
if request_method == 'PATCH':
|
||||
r = requests.patch(url, json=data)
|
||||
else:
|
||||
r = requests.post(url, json=data)
|
||||
except requests.exceptions.RequestException:
|
||||
context.status_code = None
|
||||
context.response = None
|
||||
r = request_executor.request(request_method, url, data)
|
||||
except Exception:
|
||||
context.status_code = context.response = None
|
||||
else:
|
||||
_set_response(context, r)
|
||||
|
||||
|
||||
@step('I run {cmd}')
|
||||
def do_run(context, cmd):
|
||||
cmd = ['coverage', 'run', '--source=patroni', '-p'] + shlex.split(cmd)
|
||||
cmd = [sys.executable, '-m', 'coverage', 'run', '--source=patroni', '-p'] + shlex.split(cmd)
|
||||
try:
|
||||
# XXX: Dirty hack! We need to take name/passwd from the config!
|
||||
env = os.environ.copy()
|
||||
@@ -111,7 +103,8 @@ def check_response(context, component, data):
|
||||
assert context.status_code == int(data),\
|
||||
"status code {0} != {1}, response: {2}".format(context.status_code, data, context.response)
|
||||
elif component == 'returncode':
|
||||
assert context.status_code == int(data), "return code {0} != {1}".format(context.status_code, data)
|
||||
assert context.status_code == int(data), "return code {0} != {1}, {2}".format(context.status_code,
|
||||
data, context.response)
|
||||
elif component == 'text':
|
||||
assert context.response == data.strip('"'), "response {0} does not contain {1}".format(context.response, data)
|
||||
elif component == 'output':
|
||||
@@ -121,10 +114,10 @@ def check_response(context, component, data):
|
||||
assert str(context.response[component]) == str(data), "{0} does not contain {1}".format(component, data)
|
||||
|
||||
|
||||
@step('I issue a scheduled failover from {from_host:w} to {to_host:w} in {in_seconds:d} seconds')
|
||||
def scheduled_failover(context, from_host, to_host, in_seconds):
|
||||
@step('I issue a scheduled switchover from {from_host:w} to {to_host:w} in {in_seconds:d} seconds')
|
||||
def scheduled_switchover(context, from_host, to_host, in_seconds):
|
||||
context.execute_steps(u"""
|
||||
Given I run patronictl.py failover batman --master {0} --candidate {1} --scheduled "{2}" --force
|
||||
Given I run patronictl.py switchover batman --master {0} --candidate {1} --scheduled "{2}" --force
|
||||
""".format(from_host, to_host, datetime.now(tzutc) + timedelta(seconds=int(in_seconds))))
|
||||
|
||||
|
||||
@@ -144,8 +137,8 @@ def add_tag_to_config(context, tag, value, pg_name):
|
||||
def check_http_response(context, url, value, timeout, negate=False):
|
||||
timeout *= context.timeout_multiplier
|
||||
for _ in range(int(timeout)):
|
||||
r = requests.get(url)
|
||||
if (value in r.content.decode('utf-8')) != negate:
|
||||
r = request_executor.request('GET', url)
|
||||
if (value in r.data.decode('utf-8')) != negate:
|
||||
break
|
||||
time.sleep(1)
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from behave import step
|
||||
|
||||
|
||||
select_replication_query = """
|
||||
SELECT * FROM pg_catalog.pg_stat_replication
|
||||
WHERE application_name = '{0}'
|
||||
"""
|
||||
|
||||
executable = sys.executable if os.name != 'nt' else sys.executable.replace('\\', '/')
|
||||
callback = executable + " features/callback2.py "
|
||||
|
||||
|
||||
@step('I start {name:w} with callback configured')
|
||||
def start_patroni_with_callbacks(context, name):
|
||||
return context.pctl.start(name, custom_config={
|
||||
"postgresql": {
|
||||
"callbacks": {
|
||||
"on_role_change": executable + " features/callback.py"
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@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,
|
||||
"postgresql": {
|
||||
"callbacks": {c: callback + name for c in ('on_start', 'on_stop', 'on_restart', 'on_role_change')},
|
||||
"backup_restore": {
|
||||
"command": (executable + " features/backup_restore.py --sourcedir=" +
|
||||
os.path.join(context.pctl.patroni_path, 'data', 'basebackup'))}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@step('I start {name:w} in a standby cluster {cluster_name:w} as a clone of {name2:w}')
|
||||
def start_patroni_standby_cluster(context, name, cluster_name, name2):
|
||||
# we need to remove patroni.dynamic.json in order to "bootstrap" standby cluster with existing PGDATA
|
||||
os.unlink(os.path.join(context.pctl._processes[name]._data_dir, 'patroni.dynamic.json'))
|
||||
port = context.pctl._processes[name2]._connkwargs.get('port')
|
||||
context.pctl._processes[name].update_config({
|
||||
"scope": cluster_name,
|
||||
"bootstrap": {
|
||||
"dcs": {
|
||||
"ttl": 20,
|
||||
"loop_wait": 2,
|
||||
"retry_timeout": 5,
|
||||
"standby_cluster": {
|
||||
"host": "localhost",
|
||||
"port": port,
|
||||
"primary_slot_name": "pm_1",
|
||||
"create_replica_methods": ["backup_restore", "basebackup"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"postgresql": {
|
||||
"callbacks": {c: callback + name for c in ('on_start', 'on_stop', 'on_restart', 'on_role_change')}
|
||||
}
|
||||
})
|
||||
return context.pctl.start(name)
|
||||
|
||||
|
||||
@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:
|
||||
break
|
||||
|
||||
time.sleep(1)
|
||||
else:
|
||||
assert False, "{0} is not replicating from {1} after {2} seconds".format(pg_name1, pg_name2, timeout)
|
||||
@@ -0,0 +1,49 @@
|
||||
from behave import step, then
|
||||
import time
|
||||
|
||||
|
||||
def polling_loop(timeout, interval=1):
|
||||
"""Returns an iterator that returns values until timeout has passed. Timeout is measured from start of iteration."""
|
||||
start_time = time.time()
|
||||
iteration = 0
|
||||
end_time = start_time + timeout
|
||||
while time.time() < end_time:
|
||||
yield iteration
|
||||
iteration += 1
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
@step('I start {name:w} with watchdog')
|
||||
def start_patroni_with_watchdog(context, name):
|
||||
return context.pctl.start(name, custom_config={'watchdog': True})
|
||||
|
||||
|
||||
@step('{name:w} watchdog has been pinged after {timeout:d} seconds')
|
||||
def watchdog_was_pinged(context, name, timeout):
|
||||
for _ in polling_loop(timeout):
|
||||
if context.pctl.get_watchdog(name).was_pinged:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@then('{name:w} watchdog has been closed')
|
||||
def watchdog_was_closed(context, name):
|
||||
assert context.pctl.get_watchdog(name).was_closed
|
||||
|
||||
|
||||
@step('I reset {name:w} watchdog state')
|
||||
def watchdog_reset_pinged(context, name):
|
||||
context.pctl.get_watchdog(name).reset()
|
||||
|
||||
|
||||
@then('{name:w} watchdog is triggered after {timeout:d} seconds')
|
||||
def watchdog_was_triggered(context, name, timeout):
|
||||
for _ in polling_loop(timeout):
|
||||
if context.pctl.get_watchdog(name).was_triggered:
|
||||
return True
|
||||
assert False
|
||||
|
||||
|
||||
@step('{name:w} hangs for {timeout:d} seconds')
|
||||
def patroni_hang(context, name, timeout):
|
||||
return context.pctl.patroni_hang(name, timeout)
|
||||
@@ -0,0 +1,31 @@
|
||||
Feature: watchdog
|
||||
Verify that watchdog gets pinged and triggered under appropriate circumstances.
|
||||
|
||||
Scenario: watchdog is opened and pinged
|
||||
Given I start postgres0 with watchdog
|
||||
Then postgres0 is a leader after 10 seconds
|
||||
And postgres0 role is the primary after 10 seconds
|
||||
And postgres0 watchdog has been pinged after 10 seconds
|
||||
|
||||
Scenario: watchdog is disabled during pause
|
||||
Given I run patronictl.py pause batman
|
||||
Then I receive a response returncode 0
|
||||
When I sleep for 2 seconds
|
||||
Then postgres0 watchdog has been closed
|
||||
|
||||
Scenario: watchdog is opened and pinged after resume
|
||||
Given I reset postgres0 watchdog state
|
||||
And I run patronictl.py resume batman
|
||||
Then I receive a response returncode 0
|
||||
And postgres0 watchdog has been pinged after 10 seconds
|
||||
|
||||
Scenario: watchdog is disabled when shutting down
|
||||
Given I shut down postgres0
|
||||
Then postgres0 watchdog has been closed
|
||||
|
||||
Scenario: watchdog is triggered if patroni stops responding
|
||||
Given I reset postgres0 watchdog state
|
||||
And I start postgres0 with watchdog
|
||||
Then postgres0 role is the primary after 10 seconds
|
||||
When postgres0 hangs for 30 seconds
|
||||
Then postgres0 watchdog is triggered after 30 seconds
|
||||
+18
-14
@@ -1,21 +1,25 @@
|
||||
global
|
||||
maxconn 100
|
||||
maxconn 100
|
||||
|
||||
defaults
|
||||
log global
|
||||
mode tcp
|
||||
retries 2
|
||||
timeout client 30m
|
||||
timeout connect 4s
|
||||
timeout server 30m
|
||||
timeout check 5s
|
||||
log global
|
||||
mode tcp
|
||||
retries 2
|
||||
timeout client 30m
|
||||
timeout connect 4s
|
||||
timeout server 30m
|
||||
timeout check 5s
|
||||
|
||||
frontend ft_postgresql
|
||||
bind *:5000
|
||||
default_backend bk_db
|
||||
|
||||
backend bk_db
|
||||
option httpchk
|
||||
listen stats
|
||||
mode http
|
||||
bind *:7000
|
||||
stats enable
|
||||
stats uri /
|
||||
|
||||
listen batman
|
||||
bind *:5000
|
||||
option httpchk
|
||||
http-check expect status 200
|
||||
default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
|
||||
server postgresql_127.0.0.1_5432 127.0.0.1:5432 maxconn 100 check port 8008
|
||||
server postgresql_127.0.0.1_5433 127.0.0.1:5433 maxconn 100 check port 8009
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
FROM postgres:11
|
||||
MAINTAINER Alexander Kukushkin <[email protected]>
|
||||
|
||||
RUN export DEBIAN_FRONTEND=noninteractive \
|
||||
&& echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \
|
||||
&& apt-get update -y \
|
||||
&& apt-get upgrade -y \
|
||||
&& apt-cache depends patroni | sed -n -e 's/.* Depends: \(python3-.\+\)$/\1/p' \
|
||||
| grep -Ev '^python3-(sphinx|etcd|consul|kazoo|kubernetes)' \
|
||||
| xargs apt-get install -y vim-tiny curl jq locales git python3-pip python3-wheel \
|
||||
## 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 \
|
||||
&& pip3 install setuptools \
|
||||
&& pip3 install 'git+https://github.com/zalando/patroni.git#egg=patroni[kubernetes]' \
|
||||
&& PGHOME=/home/postgres \
|
||||
&& mkdir -p $PGHOME \
|
||||
&& chown postgres $PGHOME \
|
||||
&& sed -i "s|/var/lib/postgresql.*|$PGHOME:/bin/bash|" /etc/passwd \
|
||||
# Set permissions for OpenShift
|
||||
&& chmod 775 $PGHOME \
|
||||
&& chmod 664 /etc/passwd \
|
||||
# Clean up
|
||||
&& apt-get remove -y git python3-pip python3-wheel \
|
||||
&& apt-get autoremove -y \
|
||||
&& apt-get clean -y \
|
||||
&& rm -rf /var/lib/apt/lists/* /root/.cache
|
||||
|
||||
ADD entrypoint.sh /
|
||||
|
||||
EXPOSE 5432 8008
|
||||
ENV LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 EDITOR=/usr/bin/editor
|
||||
USER postgres
|
||||
WORKDIR /home/postgres
|
||||
CMD ["/bin/bash", "/entrypoint.sh"]
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [[ $UID -ge 10000 ]]; then
|
||||
GID=$(id -g)
|
||||
sed -e "s/^postgres:x:[^:]*:[^:]*:/postgres:x:$UID:$GID:/" /etc/passwd > /tmp/passwd
|
||||
cat /tmp/passwd > /etc/passwd
|
||||
rm /tmp/passwd
|
||||
fi
|
||||
|
||||
cat > /home/postgres/patroni.yml <<__EOF__
|
||||
bootstrap:
|
||||
dcs:
|
||||
postgresql:
|
||||
use_pg_rewind: true
|
||||
initdb:
|
||||
- auth-host: md5
|
||||
- auth-local: trust
|
||||
- encoding: UTF8
|
||||
- locale: en_US.UTF-8
|
||||
- data-checksums
|
||||
pg_hba:
|
||||
- host all all 0.0.0.0/0 md5
|
||||
- host replication ${PATRONI_REPLICATION_USERNAME} ${PATRONI_KUBERNETES_POD_IP}/16 md5
|
||||
restapi:
|
||||
connect_address: '${PATRONI_KUBERNETES_POD_IP}:8008'
|
||||
postgresql:
|
||||
connect_address: '${PATRONI_KUBERNETES_POD_IP}:5432'
|
||||
authentication:
|
||||
superuser:
|
||||
password: '${PATRONI_SUPERUSER_PASSWORD}'
|
||||
replication:
|
||||
password: '${PATRONI_REPLICATION_PASSWORD}'
|
||||
__EOF__
|
||||
|
||||
unset PATRONI_SUPERUSER_PASSWORD PATRONI_REPLICATION_PASSWORD
|
||||
export KUBERNETES_NAMESPACE=$PATRONI_KUBERNETES_NAMESPACE
|
||||
export POD_NAME=$PATRONI_NAME
|
||||
|
||||
exec /usr/bin/python3 /usr/local/bin/patroni /home/postgres/patroni.yml
|
||||
@@ -0,0 +1,49 @@
|
||||
# Patroni OpenShift Configuration
|
||||
Patroni can be run in OpenShift. Based on the kubernetes configuration, the Dockerfile and Entrypoint has been modified to support the dynamic UID/GID configuration that is applied in OpenShift. This can be run under the standard `restricted` SCC.
|
||||
|
||||
# Examples
|
||||
|
||||
## Create test project
|
||||
|
||||
```
|
||||
oc new-project patroni-test
|
||||
```
|
||||
|
||||
## Build the image
|
||||
|
||||
Note: Update the references when merged upstream.
|
||||
Note: If deploying as a template for multiple users, the following commands should be performed in a shared namespace like `openshift`.
|
||||
|
||||
```
|
||||
oc import-image postgres:10 --confirm -n openshift
|
||||
oc new-build https://github.com/zalando/patroni --context-dir=kubernetes -n openshift
|
||||
```
|
||||
|
||||
## Deploy the Image
|
||||
Two configuration templates exist in [templates](templates) directory:
|
||||
- Patroni Ephemeral
|
||||
- Patroni Persistent
|
||||
|
||||
The only difference is whether or not the statefulset requests persistent storage.
|
||||
|
||||
## Create the Template
|
||||
Install the template into the `openshift` namespace if this should be shared across projects:
|
||||
|
||||
```
|
||||
oc create -f templates/template_patroni_ephemeral.yml -n openshift
|
||||
```
|
||||
|
||||
Then, from your own project:
|
||||
|
||||
```
|
||||
oc new-app patroni-pgsql-ephemeral
|
||||
```
|
||||
|
||||
Once the pods are running, two configmaps should be available:
|
||||
|
||||
```
|
||||
$ oc get configmap
|
||||
NAME DATA AGE
|
||||
patroniocp-config 0 1m
|
||||
patroniocp-leader 0 1m
|
||||
```
|
||||
@@ -0,0 +1,287 @@
|
||||
apiVersion: v1
|
||||
kind: Template
|
||||
metadata:
|
||||
name: patroni-pgsql-ephemeral
|
||||
annotations:
|
||||
description: |-
|
||||
Patroni Postgresql database cluster, without persistent storage.
|
||||
|
||||
WARNING: Any data stored will be lost upon pod destruction. Only use this template for testing.
|
||||
iconClass: icon-postgresql
|
||||
openshift.io/display-name: Patroni Postgresql (Ephemeral)
|
||||
openshift.io/long-description: This template deploys a a patroni postgresql HA cluster without persistent storage.
|
||||
tags: postgresql
|
||||
objects:
|
||||
- apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
targetPort: 5432
|
||||
sessionAffinity: None
|
||||
type: ClusterIP
|
||||
status:
|
||||
loadBalancer: {}
|
||||
- apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${PATRONI_MASTER_SERVICE_NAME}
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
targetPort: 5432
|
||||
selector:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
role: master
|
||||
sessionAffinity: None
|
||||
type: ClusterIP
|
||||
status:
|
||||
loadBalancer: {}
|
||||
- apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
stringData:
|
||||
superuser-password: ${PATRONI_SUPERUSER_PASSWORD}
|
||||
replication-password: ${PATRONI_REPLICATION_PASSWORD}
|
||||
- apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${PATRONI_REPLICA_SERVICE_NAME}
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
targetPort: 5432
|
||||
selector:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
role: replica
|
||||
sessionAffinity: None
|
||||
type: ClusterIP
|
||||
status:
|
||||
loadBalancer: {}
|
||||
- apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
generation: 3
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${APPLICATION_NAME}
|
||||
spec:
|
||||
podManagementPolicy: OrderedReady
|
||||
replicas: 3
|
||||
revisionHistoryLimit: 10
|
||||
selector:
|
||||
matchLabels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
serviceName: ${APPLICATION_NAME}
|
||||
template:
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
spec:
|
||||
containers:
|
||||
- env:
|
||||
- name: PATRONI_KUBERNETES_POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
apiVersion: v1
|
||||
fieldPath: status.podIP
|
||||
- name: PATRONI_KUBERNETES_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
apiVersion: v1
|
||||
fieldPath: metadata.namespace
|
||||
- name: PATRONI_KUBERNETES_LABELS
|
||||
value: '{application: ${APPLICATION_NAME}, cluster-name: ${PATRONI_CLUSTER_NAME}}'
|
||||
- name: PATRONI_SUPERUSER_USERNAME
|
||||
value: ${PATRONI_SUPERUSER_USERNAME}
|
||||
- name: PATRONI_SUPERUSER_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
key: superuser-password
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
- name: PATRONI_REPLICATION_USERNAME
|
||||
value: ${PATRONI_REPLICATION_USERNAME}
|
||||
- name: PATRONI_REPLICATION_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
key: replication-password
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
- name: PATRONI_SCOPE
|
||||
value: ${PATRONI_CLUSTER_NAME}
|
||||
- name: PATRONI_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
apiVersion: v1
|
||||
fieldPath: metadata.name
|
||||
- name: PATRONI_POSTGRESQL_DATA_DIR
|
||||
value: /home/postgres/pgdata/pgroot/data
|
||||
- name: PATRONI_POSTGRESQL_PGPASS
|
||||
value: /tmp/pgpass
|
||||
- name: PATRONI_POSTGRESQL_LISTEN
|
||||
value: 0.0.0.0:5432
|
||||
- name: PATRONI_RESTAPI_LISTEN
|
||||
value: 0.0.0.0:8008
|
||||
image: docker-registry.default.svc:5000/${NAMESPACE}/patroni:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
name: ${APPLICATION_NAME}
|
||||
ports:
|
||||
- containerPort: 8008
|
||||
protocol: TCP
|
||||
- containerPort: 5432
|
||||
protocol: TCP
|
||||
resources: {}
|
||||
terminationMessagePath: /dev/termination-log
|
||||
terminationMessagePolicy: File
|
||||
volumeMounts:
|
||||
- mountPath: /home/postgres/pgdata
|
||||
name: pgdata
|
||||
dnsPolicy: ClusterFirst
|
||||
restartPolicy: Always
|
||||
schedulerName: default-scheduler
|
||||
securityContext: {}
|
||||
serviceAccount: ${SERVICE_ACCOUNT}
|
||||
serviceAccountName: ${SERVICE_ACCOUNT}
|
||||
terminationGracePeriodSeconds: 0
|
||||
volumes:
|
||||
- name: pgdata
|
||||
emptyDir: {}
|
||||
updateStrategy:
|
||||
type: OnDelete
|
||||
- apiVersion: v1
|
||||
kind: Endpoints
|
||||
metadata:
|
||||
name: ${APPLICATION_NAME}
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
subsets: []
|
||||
- apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
- apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
rules:
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- configmaps
|
||||
verbs:
|
||||
- create
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
# delete is required only for 'patronictl remove'
|
||||
- delete
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- endpoints
|
||||
verbs:
|
||||
- get
|
||||
- patch
|
||||
- update
|
||||
# the following three privileges are necessary only when using endpoints
|
||||
- create
|
||||
- list
|
||||
- watch
|
||||
# delete is required only for for 'patronictl remove'
|
||||
- delete
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- pods
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
- apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: Role
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
parameters:
|
||||
- description: The name of the application for labelling all artifacts.
|
||||
displayName: Application Name
|
||||
name: APPLICATION_NAME
|
||||
value: patroni-ephemeral
|
||||
- description: The name of the patroni-pgsql cluster.
|
||||
displayName: Cluster Name
|
||||
name: PATRONI_CLUSTER_NAME
|
||||
value: patroni-ephemeral
|
||||
- description: The name of the OpenShift Service exposed for the patroni-ephemeral-master container.
|
||||
displayName: Master service name.
|
||||
name: PATRONI_MASTER_SERVICE_NAME
|
||||
value: patroni-ephemeral-master
|
||||
- description: The name of the OpenShift Service exposed for the patroni-ephemeral-replica containers.
|
||||
displayName: Replica service name.
|
||||
name: PATRONI_REPLICA_SERVICE_NAME
|
||||
value: patroni-ephemeral-replica
|
||||
- description: Maximum amount of memory the container can use.
|
||||
displayName: Memory Limit
|
||||
name: MEMORY_LIMIT
|
||||
value: 512Mi
|
||||
- description: The OpenShift Namespace where the patroni and postgresql ImageStream resides.
|
||||
displayName: ImageStream Namespace
|
||||
name: NAMESPACE
|
||||
value: openshift
|
||||
- description: Username of the superuser account for initialization.
|
||||
displayName: Superuser Username
|
||||
name: PATRONI_SUPERUSER_USERNAME
|
||||
value: postgres
|
||||
- description: Password of the superuser account for initialization.
|
||||
displayName: Superuser Passsword
|
||||
name: PATRONI_SUPERUSER_PASSWORD
|
||||
value: postgres
|
||||
- description: Username of the replication account for initialization.
|
||||
displayName: Replication Username
|
||||
name: PATRONI_REPLICATION_USERNAME
|
||||
value: postgres
|
||||
- description: Password of the replication account for initialization.
|
||||
displayName: Repication Passsword
|
||||
name: PATRONI_REPLICATION_PASSWORD
|
||||
value: postgres
|
||||
- description: Service account name used for pods and rolebindings to form a cluster in the project.
|
||||
displayName: Service Account
|
||||
name: SERVICE_ACCOUNT
|
||||
value: patroniocp
|
||||
@@ -0,0 +1,317 @@
|
||||
apiVersion: v1
|
||||
kind: Template
|
||||
metadata:
|
||||
name: patroni-pgsql-persistent
|
||||
annotations:
|
||||
description: |-
|
||||
Patroni Postgresql database cluster, with persistent storage.
|
||||
|
||||
WARNING: Any data stored will be lost upon pod destruction. Only use this template for testing.
|
||||
iconClass: icon-postgresql
|
||||
openshift.io/display-name: Patroni Postgresql (Persistent)
|
||||
openshift.io/long-description: This template deploys a a patroni postgresql HA cluster without persistent storage.
|
||||
tags: postgresql
|
||||
objects:
|
||||
- apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
targetPort: 5432
|
||||
sessionAffinity: None
|
||||
type: ClusterIP
|
||||
status:
|
||||
loadBalancer: {}
|
||||
- apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${PATRONI_MASTER_SERVICE_NAME}
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
targetPort: 5432
|
||||
selector:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
role: master
|
||||
sessionAffinity: None
|
||||
type: ClusterIP
|
||||
status:
|
||||
loadBalancer: {}
|
||||
- apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
stringData:
|
||||
superuser-password: ${PATRONI_SUPERUSER_PASSWORD}
|
||||
replication-password: ${PATRONI_REPLICATION_PASSWORD}
|
||||
- apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${PATRONI_REPLICA_SERVICE_NAME}
|
||||
spec:
|
||||
ports:
|
||||
- port: 5432
|
||||
protocol: TCP
|
||||
targetPort: 5432
|
||||
selector:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
role: replica
|
||||
sessionAffinity: None
|
||||
type: ClusterIP
|
||||
status:
|
||||
loadBalancer: {}
|
||||
- apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
generation: 3
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
name: ${APPLICATION_NAME}
|
||||
spec:
|
||||
podManagementPolicy: OrderedReady
|
||||
replicas: 3
|
||||
revisionHistoryLimit: 10
|
||||
selector:
|
||||
matchLabels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
serviceName: ${APPLICATION_NAME}
|
||||
template:
|
||||
metadata:
|
||||
creationTimestamp: null
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
spec:
|
||||
initContainers:
|
||||
- command:
|
||||
- sh
|
||||
- -c
|
||||
- "mkdir -p /home/postgres/pgdata/pgroot/data && chmod 0700 /home/postgres/pgdata/pgroot/data"
|
||||
image: docker-registry.default.svc:5000/${NAMESPACE}/patroni:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
name: fix-perms
|
||||
resources: {}
|
||||
terminationMessagePath: /dev/termination-log
|
||||
terminationMessagePolicy: File
|
||||
volumeMounts:
|
||||
- mountPath: /home/postgres/pgdata
|
||||
name: ${APPLICATION_NAME}
|
||||
containers:
|
||||
- env:
|
||||
- name: PATRONI_KUBERNETES_POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
apiVersion: v1
|
||||
fieldPath: status.podIP
|
||||
- name: PATRONI_KUBERNETES_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
apiVersion: v1
|
||||
fieldPath: metadata.namespace
|
||||
- name: PATRONI_KUBERNETES_LABELS
|
||||
value: '{application: ${APPLICATION_NAME}, cluster-name: ${PATRONI_CLUSTER_NAME}}'
|
||||
- name: PATRONI_SUPERUSER_USERNAME
|
||||
value: ${PATRONI_SUPERUSER_USERNAME}
|
||||
- name: PATRONI_SUPERUSER_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
key: superuser-password
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
- name: PATRONI_REPLICATION_USERNAME
|
||||
value: ${PATRONI_REPLICATION_USERNAME}
|
||||
- name: PATRONI_REPLICATION_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
key: replication-password
|
||||
name: ${PATRONI_CLUSTER_NAME}
|
||||
- name: PATRONI_SCOPE
|
||||
value: ${PATRONI_CLUSTER_NAME}
|
||||
- name: PATRONI_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
apiVersion: v1
|
||||
fieldPath: metadata.name
|
||||
- name: PATRONI_POSTGRESQL_DATA_DIR
|
||||
value: /home/postgres/pgdata/pgroot/data
|
||||
- name: PATRONI_POSTGRESQL_PGPASS
|
||||
value: /tmp/pgpass
|
||||
- name: PATRONI_POSTGRESQL_LISTEN
|
||||
value: 0.0.0.0:5432
|
||||
- name: PATRONI_RESTAPI_LISTEN
|
||||
value: 0.0.0.0:8008
|
||||
image: docker-registry.default.svc:5000/${NAMESPACE}/patroni:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
name: ${APPLICATION_NAME}
|
||||
ports:
|
||||
- containerPort: 8008
|
||||
protocol: TCP
|
||||
- containerPort: 5432
|
||||
protocol: TCP
|
||||
resources: {}
|
||||
terminationMessagePath: /dev/termination-log
|
||||
terminationMessagePolicy: File
|
||||
volumeMounts:
|
||||
- mountPath: /home/postgres/pgdata
|
||||
name: ${APPLICATION_NAME}
|
||||
dnsPolicy: ClusterFirst
|
||||
restartPolicy: Always
|
||||
schedulerName: default-scheduler
|
||||
securityContext: {}
|
||||
serviceAccount: ${SERVICE_ACCOUNT}
|
||||
serviceAccountName: ${SERVICE_ACCOUNT}
|
||||
terminationGracePeriodSeconds: 0
|
||||
volumes:
|
||||
- name: ${APPLICATION_NAME}
|
||||
persistentVolumeClaim:
|
||||
claimName: ${APPLICATION_NAME}
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
name: ${APPLICATION_NAME}
|
||||
spec:
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: ${PVC_SIZE}
|
||||
updateStrategy:
|
||||
type: OnDelete
|
||||
- apiVersion: v1
|
||||
kind: Endpoints
|
||||
metadata:
|
||||
name: ${APPLICATION_NAME}
|
||||
labels:
|
||||
application: ${APPLICATION_NAME}
|
||||
cluster-name: ${PATRONI_CLUSTER_NAME}
|
||||
subsets: []
|
||||
- apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
- apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
rules:
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- configmaps
|
||||
verbs:
|
||||
- create
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
# delete is required only for 'patronictl remove'
|
||||
- delete
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- endpoints
|
||||
verbs:
|
||||
- get
|
||||
- patch
|
||||
- update
|
||||
# the following three privileges are necessary only when using endpoints
|
||||
- create
|
||||
- list
|
||||
- watch
|
||||
# delete is required only for for 'patronictl remove'
|
||||
- delete
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- pods
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
- apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: Role
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: ${SERVICE_ACCOUNT}
|
||||
parameters:
|
||||
- description: The name of the application for labelling all artifacts.
|
||||
displayName: Application Name
|
||||
name: APPLICATION_NAME
|
||||
value: patroni-persistent
|
||||
- description: The name of the patroni-pgsql cluster.
|
||||
displayName: Cluster Name
|
||||
name: PATRONI_CLUSTER_NAME
|
||||
value: patroni-persistent
|
||||
- description: The name of the OpenShift Service exposed for the patroni-persistent-master container.
|
||||
displayName: Master service name.
|
||||
name: PATRONI_MASTER_SERVICE_NAME
|
||||
value: patroni-persistent-master
|
||||
- description: The name of the OpenShift Service exposed for the patroni-persistent-replica containers.
|
||||
displayName: Replica service name.
|
||||
name: PATRONI_REPLICA_SERVICE_NAME
|
||||
value: patroni-persistent-replica
|
||||
- description: Maximum amount of memory the container can use.
|
||||
displayName: Memory Limit
|
||||
name: MEMORY_LIMIT
|
||||
value: 512Mi
|
||||
- description: The OpenShift Namespace where the patroni and postgresql ImageStream resides.
|
||||
displayName: ImageStream Namespace
|
||||
name: NAMESPACE
|
||||
value: openshift
|
||||
- description: Username of the superuser account for initialization.
|
||||
displayName: Superuser Username
|
||||
name: PATRONI_SUPERUSER_USERNAME
|
||||
value: postgres
|
||||
- description: Password of the superuser account for initialization.
|
||||
displayName: Superuser Passsword
|
||||
name: PATRONI_SUPERUSER_PASSWORD
|
||||
value: postgres
|
||||
- description: Username of the replication account for initialization.
|
||||
displayName: Replication Username
|
||||
name: PATRONI_REPLICATION_USERNAME
|
||||
value: postgres
|
||||
- description: Password of the replication account for initialization.
|
||||
displayName: Repication Passsword
|
||||
name: PATRONI_REPLICATION_PASSWORD
|
||||
value: postgres
|
||||
- description: Service account name used for pods and rolebindings to form a cluster in the project.
|
||||
displayName: Service Account
|
||||
name: SERVICE_ACCOUNT
|
||||
value: patroni-persistent
|
||||
- description: The size of the persistent volume to create.
|
||||
displayName: Persistent Volume Size
|
||||
name: PVC_SIZE
|
||||
value: 5Gi
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
pipeline {
|
||||
agent any
|
||||
stages {
|
||||
stage ('Deploy test pod'){
|
||||
when {
|
||||
expression {
|
||||
openshift.withCluster() {
|
||||
openshift.withProject() {
|
||||
return !openshift.selector( "dc", "pgbench" ).exists()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
openshift.withCluster() {
|
||||
openshift.withProject() {
|
||||
def pgbench = openshift.newApp( "https://github.com/stewartshea/docker-pgbench/", "--name=pgbench", "-e PGPASSWORD=postgres", "-e PGUSER=postgres", "-e PGHOST=patroni-persistent-master", "-e PGDATABASE=postgres", "-e TEST_CLIENT_COUNT=20", "-e TEST_DURATION=120" )
|
||||
def pgbenchdc = openshift.selector( "dc", "pgbench" )
|
||||
timeout(5) {
|
||||
pgbenchdc.rollout().status()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stage ('Run benchmark Test'){
|
||||
steps {
|
||||
sh '''
|
||||
oc exec $(oc get pods -l app=pgbench | grep Running | awk '{print $1}') ./test.sh
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage ('Clean up pgtest pod'){
|
||||
steps {
|
||||
sh '''
|
||||
oc delete all -l app=pgbench
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# Jenkins Test
|
||||
This pipeline test will create a separate deployment config for a pgbench pod and execute a test against the patroni cluster. This is a sample and should be customized.
|
||||
@@ -0,0 +1,212 @@
|
||||
# headless service to avoid deletion of patronidemo-config endpoint
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: patronidemo-config
|
||||
labels:
|
||||
application: patroni
|
||||
cluster-name: patronidemo
|
||||
spec:
|
||||
clusterIP: None
|
||||
|
||||
---
|
||||
apiVersion: apps/v1beta1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: &cluster_name patronidemo
|
||||
labels:
|
||||
application: patroni
|
||||
cluster-name: *cluster_name
|
||||
spec:
|
||||
replicas: 3
|
||||
serviceName: *cluster_name
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
application: patroni
|
||||
cluster-name: *cluster_name
|
||||
spec:
|
||||
serviceAccountName: patronidemo
|
||||
containers:
|
||||
- name: *cluster_name
|
||||
image: patroni # docker build -t patroni .
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 8008
|
||||
protocol: TCP
|
||||
- containerPort: 5432
|
||||
protocol: TCP
|
||||
volumeMounts:
|
||||
- mountPath: /home/postgres/pgdata
|
||||
name: pgdata
|
||||
env:
|
||||
- name: PATRONI_KUBERNETES_POD_IP
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: status.podIP
|
||||
- name: PATRONI_KUBERNETES_NAMESPACE
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.namespace
|
||||
- name: PATRONI_KUBERNETES_USE_ENDPOINTS
|
||||
value: 'true'
|
||||
- name: PATRONI_KUBERNETES_LABELS
|
||||
value: '{application: patroni, cluster-name: patronidemo}'
|
||||
- name: PATRONI_SUPERUSER_USERNAME
|
||||
value: postgres
|
||||
- name: PATRONI_SUPERUSER_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: *cluster_name
|
||||
key: superuser-password
|
||||
- name: PATRONI_REPLICATION_USERNAME
|
||||
value: standby
|
||||
- name: PATRONI_REPLICATION_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: *cluster_name
|
||||
key: replication-password
|
||||
- name: PATRONI_SCOPE
|
||||
value: *cluster_name
|
||||
- name: PATRONI_NAME
|
||||
valueFrom:
|
||||
fieldRef:
|
||||
fieldPath: metadata.name
|
||||
- name: PATRONI_POSTGRESQL_DATA_DIR
|
||||
value: /home/postgres/pgdata/pgroot/data
|
||||
- name: PATRONI_POSTGRESQL_PGPASS
|
||||
value: /tmp/pgpass
|
||||
- name: PATRONI_POSTGRESQL_LISTEN
|
||||
value: '0.0.0.0:5432'
|
||||
- name: PATRONI_RESTAPI_LISTEN
|
||||
value: '0.0.0.0:8008'
|
||||
terminationGracePeriodSeconds: 0
|
||||
volumes:
|
||||
- name: pgdata
|
||||
emptyDir: {}
|
||||
# volumeClaimTemplates:
|
||||
# - metadata:
|
||||
# labels:
|
||||
# application: spilo
|
||||
# spilo-cluster: *cluster_name
|
||||
# annotations:
|
||||
# volume.alpha.kubernetes.io/storage-class: anything
|
||||
# name: pgdata
|
||||
# spec:
|
||||
# accessModes:
|
||||
# - ReadWriteOnce
|
||||
# resources:
|
||||
# requests:
|
||||
# storage: 5Gi
|
||||
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Endpoints
|
||||
metadata:
|
||||
name: &cluster_name patronidemo
|
||||
labels:
|
||||
application: patroni
|
||||
cluster-name: *cluster_name
|
||||
subsets: []
|
||||
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: &cluster_name patronidemo
|
||||
labels:
|
||||
application: patroni
|
||||
cluster-name: *cluster_name
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- port: 5432
|
||||
targetPort: 5432
|
||||
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: &cluster_name patronidemo
|
||||
labels:
|
||||
application: patroni
|
||||
cluster-name: *cluster_name
|
||||
type: Opaque
|
||||
data:
|
||||
superuser-password: emFsYW5kbw==
|
||||
replication-password: cmVwLXBhc3M=
|
||||
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ServiceAccount
|
||||
metadata:
|
||||
name: patronidemo
|
||||
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: Role
|
||||
metadata:
|
||||
name: patronidemo
|
||||
rules:
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- configmaps
|
||||
verbs:
|
||||
- create
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
# delete and deletecollection are required only for 'patronictl remove'
|
||||
- delete
|
||||
- deletecollection
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- endpoints
|
||||
verbs:
|
||||
- get
|
||||
- patch
|
||||
- update
|
||||
# the following three privileges are necessary only when using endpoints
|
||||
- create
|
||||
- list
|
||||
- watch
|
||||
# delete and deletecollection are required only for for 'patronictl remove'
|
||||
- delete
|
||||
- deletecollection
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- pods
|
||||
verbs:
|
||||
- get
|
||||
- list
|
||||
- patch
|
||||
- update
|
||||
- watch
|
||||
# The following privilege is only necessary for creation of headless service
|
||||
# for patronidemo-config endpoint, in order to prevent cleaning it up by the
|
||||
# k8s master. You can avoid giving this privilege by explicitly creating the
|
||||
# service like it is done in this manifest (lines 2..10)
|
||||
- apiGroups:
|
||||
- ""
|
||||
resources:
|
||||
- services
|
||||
verbs:
|
||||
- create
|
||||
|
||||
---
|
||||
apiVersion: rbac.authorization.k8s.io/v1
|
||||
kind: RoleBinding
|
||||
metadata:
|
||||
name: patronidemo
|
||||
roleRef:
|
||||
apiGroup: rbac.authorization.k8s.io
|
||||
kind: Role
|
||||
name: patronidemo
|
||||
subjects:
|
||||
- kind: ServiceAccount
|
||||
name: patronidemo
|
||||
+120
-50
@@ -4,28 +4,38 @@ import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
from patroni.version import __version__
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PATRONI_ENV_PREFIX = 'PATRONI_'
|
||||
KUBERNETES_ENV_PREFIX = 'KUBERNETES_'
|
||||
|
||||
|
||||
class Patroni(object):
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, conf):
|
||||
from patroni.api import RestApiServer
|
||||
from patroni.config import Config
|
||||
from patroni.dcs import get_dcs
|
||||
from patroni.ha import Ha
|
||||
from patroni.log import PatroniLogger
|
||||
from patroni.postgresql import Postgresql
|
||||
from patroni.version import __version__
|
||||
from patroni.request import PatroniRequest
|
||||
from patroni.watchdog import Watchdog
|
||||
|
||||
self.setup_signal_handlers()
|
||||
|
||||
self.version = __version__
|
||||
self.config = Config()
|
||||
self.logger = PatroniLogger()
|
||||
self.config = conf
|
||||
self.logger.reload_config(self.config.get('log', {}))
|
||||
self.dcs = get_dcs(self.config)
|
||||
self.watchdog = Watchdog(self.config)
|
||||
self.load_dynamic_configuration()
|
||||
|
||||
self.postgresql = Postgresql(self.config['postgresql'])
|
||||
self.api = RestApiServer(self, self.config['restapi'])
|
||||
self.request = PatroniRequest(self.config, True)
|
||||
self.ha = Ha(self)
|
||||
|
||||
self.tags = self.get_tags()
|
||||
@@ -37,15 +47,17 @@ class Patroni(object):
|
||||
while True:
|
||||
try:
|
||||
cluster = self.dcs.get_cluster()
|
||||
if cluster and cluster.config:
|
||||
if cluster and cluster.config and cluster.config.data:
|
||||
if self.config.set_dynamic_configuration(cluster.config):
|
||||
self.dcs.reload_config(self.config)
|
||||
self.watchdog.reload_config(self.config)
|
||||
elif not self.config.dynamic_configuration and 'bootstrap' in self.config:
|
||||
if self.config.set_dynamic_configuration(self.config['bootstrap']['dcs']):
|
||||
self.dcs.reload_config(self.config)
|
||||
break
|
||||
except DCSError:
|
||||
logger.warning('Can not get cluster from dcs')
|
||||
time.sleep(5)
|
||||
|
||||
def get_tags(self):
|
||||
return {tag: value for tag, value in self.config.get('tags', {}).items()
|
||||
@@ -59,12 +71,16 @@ class Patroni(object):
|
||||
def nosync(self):
|
||||
return bool(self.tags.get('nosync', False))
|
||||
|
||||
def reload_config(self):
|
||||
def reload_config(self, sighup=False):
|
||||
try:
|
||||
self.tags = self.get_tags()
|
||||
self.dcs.reload_config(self.config)
|
||||
self.logger.reload_config(self.config.get('log', {}))
|
||||
self.watchdog.reload_config(self.config)
|
||||
if sighup:
|
||||
self.request.reload_config(self.config)
|
||||
self.api.reload_config(self.config['restapi'])
|
||||
self.postgresql.reload_config(self.config['postgresql'])
|
||||
self.postgresql.reload_config(self.config['postgresql'], sighup)
|
||||
self.dcs.reload_config(self.config)
|
||||
except Exception:
|
||||
logger.exception('Failed to reload config_file=%s', self.config.config_file)
|
||||
|
||||
@@ -76,9 +92,10 @@ class Patroni(object):
|
||||
self._received_sighup = True
|
||||
|
||||
def sigterm_handler(self, *args):
|
||||
if not self._received_sigterm:
|
||||
self._received_sigterm = True
|
||||
sys.exit()
|
||||
with self._sigterm_lock:
|
||||
if not self._received_sigterm:
|
||||
self._received_sigterm = True
|
||||
sys.exit()
|
||||
|
||||
@property
|
||||
def noloadbalance(self):
|
||||
@@ -97,78 +114,127 @@ class Patroni(object):
|
||||
elif self.ha.watch(nap_time):
|
||||
self.next_run = time.time()
|
||||
|
||||
@property
|
||||
def received_sigterm(self):
|
||||
with self._sigterm_lock:
|
||||
return self._received_sigterm
|
||||
|
||||
def run(self):
|
||||
self.api.start()
|
||||
self.logger.start()
|
||||
self.next_run = time.time()
|
||||
|
||||
while not self._received_sigterm:
|
||||
while not self.received_sigterm:
|
||||
if self._received_sighup:
|
||||
self._received_sighup = False
|
||||
if self.config.reload_local_configuration():
|
||||
self.reload_config()
|
||||
self.reload_config(True)
|
||||
else:
|
||||
self.postgresql.config.reload_config(self.config['postgresql'], True)
|
||||
|
||||
logger.info(self.ha.run_cycle())
|
||||
|
||||
cluster = self.dcs.cluster
|
||||
if cluster and cluster.config and self.config.set_dynamic_configuration(cluster.config):
|
||||
if self.dcs.cluster and self.dcs.cluster.config and self.dcs.cluster.config.data \
|
||||
and self.config.set_dynamic_configuration(self.dcs.cluster.config):
|
||||
self.reload_config()
|
||||
|
||||
if not self.postgresql.data_directory_empty():
|
||||
if self.postgresql.role != 'uninitialized':
|
||||
self.config.save_cache()
|
||||
|
||||
self.schedule_next_run()
|
||||
|
||||
def setup_signal_handlers(self):
|
||||
from threading import Lock
|
||||
|
||||
self._received_sighup = False
|
||||
self._sigterm_lock = Lock()
|
||||
self._received_sigterm = False
|
||||
signal.signal(signal.SIGHUP, self.sighup_handler)
|
||||
if os.name != 'nt':
|
||||
signal.signal(signal.SIGHUP, self.sighup_handler)
|
||||
signal.signal(signal.SIGTERM, self.sigterm_handler)
|
||||
|
||||
def shutdown(self):
|
||||
with self._sigterm_lock:
|
||||
self._received_sigterm = True
|
||||
try:
|
||||
self.api.shutdown()
|
||||
except Exception:
|
||||
logger.exception('Exception during RestApi.shutdown')
|
||||
try:
|
||||
self.ha.shutdown()
|
||||
except Exception:
|
||||
logger.exception('Exception during Ha.shutdown')
|
||||
self.logger.shutdown()
|
||||
|
||||
|
||||
def patroni_main():
|
||||
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)
|
||||
logging.getLogger('requests').setLevel(logging.WARNING)
|
||||
import argparse
|
||||
|
||||
patroni = Patroni()
|
||||
from multiprocessing import freeze_support
|
||||
from patroni.config import Config, ConfigParseError
|
||||
from patroni.validator import schema
|
||||
|
||||
freeze_support()
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__))
|
||||
parser.add_argument('--validate-config', action='store_true', help='Run config validator and exit')
|
||||
parser.add_argument('configfile', nargs='?', default='',
|
||||
help='Patroni may also read the configuration from the {0} environment variable'
|
||||
.format(Config.PATRONI_CONFIG_VARIABLE))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.validate_config:
|
||||
conf = Config(args.configfile, validator=schema)
|
||||
sys.exit()
|
||||
else:
|
||||
conf = Config(args.configfile)
|
||||
except ConfigParseError as e:
|
||||
if e.value:
|
||||
print(e.value)
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
patroni = Patroni(conf)
|
||||
try:
|
||||
patroni.run()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
patroni.api.shutdown()
|
||||
if patroni.ha.is_paused():
|
||||
logger.info('Leader key is not deleted and Postgresql is not stopped due paused state')
|
||||
else:
|
||||
patroni.ha.while_not_sync_standby(lambda: patroni.postgresql.stop(checkpoint=False))
|
||||
patroni.dcs.delete_leader()
|
||||
patroni.shutdown()
|
||||
|
||||
|
||||
def pg_ctl_start(args):
|
||||
import subprocess
|
||||
postmaster = subprocess.Popen(args)
|
||||
print(postmaster.pid)
|
||||
def fatal(string, *args):
|
||||
sys.stderr.write('FATAL: ' + string.format(*args) + '\n')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def call_self(args, **kwargs):
|
||||
"""This function executes Patroni once again with provided arguments.
|
||||
def check_psycopg2():
|
||||
min_psycopg2 = (2, 5, 4)
|
||||
min_psycopg2_str = '.'.join(map(str, min_psycopg2))
|
||||
|
||||
:args: list of arguments to call Patroni with.
|
||||
:returns: `Popen` object"""
|
||||
def parse_version(version):
|
||||
for e in version.split('.'):
|
||||
try:
|
||||
yield int(e)
|
||||
except ValueError:
|
||||
break
|
||||
|
||||
exe = [sys.executable]
|
||||
if not getattr(sys, 'frozen', False): # Binary distribution?
|
||||
exe.append(sys.argv[0])
|
||||
|
||||
import subprocess
|
||||
return subprocess.Popen(exe + args, **kwargs)
|
||||
try:
|
||||
import psycopg2
|
||||
version_str = psycopg2.__version__.split(' ')[0]
|
||||
version = tuple(parse_version(version_str))
|
||||
if version < min_psycopg2:
|
||||
fatal('Patroni requires psycopg2>={0}, but only {1} is available', min_psycopg2_str, version_str)
|
||||
except ImportError:
|
||||
fatal('Patroni requires psycopg2>={0} or psycopg2-binary', min_psycopg2_str)
|
||||
|
||||
|
||||
def main():
|
||||
if os.getpid() != 1:
|
||||
if len(sys.argv) > 5 and sys.argv[1] == 'pg_ctl_start':
|
||||
return pg_ctl_start(sys.argv[2:])
|
||||
check_psycopg2()
|
||||
return patroni_main()
|
||||
|
||||
# Patroni started with PID=1, it looks like we are in the container
|
||||
pid = 0
|
||||
|
||||
# Looks like we are in a docker, so we will act like init
|
||||
@@ -179,7 +245,7 @@ def main():
|
||||
if ret == (0, 0):
|
||||
break
|
||||
elif ret[0] != pid:
|
||||
logging.info('Reaped pid=%s, exit status=%s', *ret)
|
||||
logger.info('Reaped pid=%s, exit status=%s', *ret)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@@ -187,14 +253,18 @@ def main():
|
||||
if pid:
|
||||
os.kill(pid, signo)
|
||||
|
||||
signal.signal(signal.SIGCHLD, sigchld_handler)
|
||||
signal.signal(signal.SIGHUP, passtochild)
|
||||
if os.name != 'nt':
|
||||
signal.signal(signal.SIGCHLD, sigchld_handler)
|
||||
signal.signal(signal.SIGHUP, passtochild)
|
||||
signal.signal(signal.SIGQUIT, passtochild)
|
||||
signal.signal(signal.SIGUSR1, passtochild)
|
||||
signal.signal(signal.SIGUSR2, passtochild)
|
||||
signal.signal(signal.SIGINT, passtochild)
|
||||
signal.signal(signal.SIGUSR1, passtochild)
|
||||
signal.signal(signal.SIGUSR2, passtochild)
|
||||
signal.signal(signal.SIGQUIT, passtochild)
|
||||
signal.signal(signal.SIGABRT, passtochild)
|
||||
signal.signal(signal.SIGTERM, passtochild)
|
||||
|
||||
patroni = call_self(sys.argv[1:])
|
||||
import multiprocessing
|
||||
patroni = multiprocessing.Process(target=patroni_main)
|
||||
patroni.start()
|
||||
pid = patroni.pid
|
||||
patroni.wait()
|
||||
patroni.join()
|
||||
|
||||
+309
-149
@@ -1,14 +1,19 @@
|
||||
import base64
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import psycopg2
|
||||
import time
|
||||
import traceback
|
||||
import dateutil.parser
|
||||
import datetime
|
||||
import os
|
||||
import six
|
||||
import socket
|
||||
|
||||
from patroni.exceptions import PostgresConnectionException
|
||||
from patroni.utils import deep_compare, patch_config, Retry, RetryFailedError, is_valid_pg_version, parse_int, tzutc
|
||||
from patroni.exceptions import PostgresConnectionException, PostgresException
|
||||
from patroni.postgresql.misc import postgres_version_to_int
|
||||
from patroni.utils import deep_compare, parse_bool, patch_config, Retry, \
|
||||
RetryFailedError, parse_int, split_host_port, tzutc, uri, cluster_as_json
|
||||
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
|
||||
from six.moves.socketserver import ThreadingMixIn
|
||||
from threading import Thread
|
||||
@@ -16,20 +21,6 @@ from threading import Thread
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def check_auth(func):
|
||||
"""Decorator function to check authorization header.
|
||||
|
||||
Usage example:
|
||||
@check_auth
|
||||
def do_PUT_foo():
|
||||
pass
|
||||
"""
|
||||
def wrapper(handler):
|
||||
if handler.check_auth_header():
|
||||
return func(handler)
|
||||
return wrapper
|
||||
|
||||
|
||||
class RestApiHandler(BaseHTTPRequestHandler):
|
||||
|
||||
def _write_response(self, status_code, body, content_type='text/html', headers=None):
|
||||
@@ -45,14 +36,20 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
def _write_json_response(self, status_code, response):
|
||||
self._write_response(status_code, json.dumps(response), content_type='application/json')
|
||||
|
||||
def send_auth_request(self, body):
|
||||
headers = {'WWW-Authenticate': 'Basic realm="' + self.server.patroni.__class__.__name__ + '"'}
|
||||
self._write_response(401, body, headers=headers)
|
||||
def check_auth(func):
|
||||
"""Decorator function to check authorization header or client certificates
|
||||
|
||||
def check_auth_header(self):
|
||||
auth_header = self.headers.get('Authorization')
|
||||
status = self.server.check_auth_header(auth_header)
|
||||
return not status or self.send_auth_request(status)
|
||||
Usage example:
|
||||
@check_auth
|
||||
def do_PUT_foo():
|
||||
pass
|
||||
"""
|
||||
|
||||
def wrapper(self, *args, **kwargs):
|
||||
if self.server.check_auth(self):
|
||||
return func(self, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
def _write_status_response(self, status_code, response):
|
||||
patroni = self.server.patroni
|
||||
@@ -68,41 +65,76 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
response['scheduled_restart'] = patroni.scheduled_restart.copy()
|
||||
del response['scheduled_restart']['postmaster_start_time']
|
||||
response['scheduled_restart']['schedule'] = (response['scheduled_restart']['schedule']).isoformat()
|
||||
if not patroni.ha.watchdog.is_healthy:
|
||||
response['watchdog_failed'] = True
|
||||
if patroni.ha.is_paused():
|
||||
response['pause'] = True
|
||||
qsize = patroni.logger.queue_size
|
||||
if qsize > patroni.logger.NORMAL_LOG_QUEUE_SIZE:
|
||||
response['logger_queue_size'] = qsize
|
||||
lost = patroni.logger.records_lost
|
||||
if lost:
|
||||
response['logger_records_lost'] = lost
|
||||
self._write_json_response(status_code, response)
|
||||
|
||||
def do_GET(self, write_status_code_only=False):
|
||||
"""Default method for processing all GET requests which can not be routed to other methods"""
|
||||
|
||||
time_start = time.time()
|
||||
request_type = 'OPTIONS' if write_status_code_only else 'GET'
|
||||
|
||||
path = '/master' if self.path == '/' else self.path
|
||||
response = self.get_postgresql_status()
|
||||
|
||||
patroni = self.server.patroni
|
||||
cluster = patroni.dcs.cluster
|
||||
if cluster: # dcs available
|
||||
if cluster.leader and cluster.leader.name == patroni.postgresql.name: # is_leader
|
||||
status_code = 200 if 'master' in path else 503
|
||||
elif 'role' not in response:
|
||||
status_code = 503
|
||||
elif response['role'] == 'master': # running as master but without leader lock!!!!
|
||||
status_code = 503
|
||||
elif response['role'] in path: # response['role'] != 'master'
|
||||
status_code = 503 if patroni.noloadbalance else 200
|
||||
|
||||
replica_status_code = 200 if not patroni.noloadbalance and \
|
||||
response.get('role') == 'replica' and response.get('state') == 'running' else 503
|
||||
|
||||
if not cluster and patroni.ha.is_paused():
|
||||
primary_status_code = 200 if response.get('role') == 'master' else 503
|
||||
standby_leader_status_code = 200 if response.get('role') == 'standby_leader' else 503
|
||||
elif patroni.ha.is_leader():
|
||||
if patroni.ha.is_standby_cluster():
|
||||
primary_status_code = replica_status_code = 503
|
||||
standby_leader_status_code = 200 if response.get('role') in ('replica', 'standby_leader') else 503
|
||||
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
|
||||
primary_status_code = 200
|
||||
standby_leader_status_code = 503
|
||||
else:
|
||||
status_code = 503
|
||||
primary_status_code = standby_leader_status_code = 503
|
||||
|
||||
status_code = 503
|
||||
|
||||
if 'standby_leader' in path or 'standby-leader' in path:
|
||||
status_code = standby_leader_status_code
|
||||
elif 'master' in path or 'leader' in path or 'primary' in path or 'read-write' in path:
|
||||
status_code = primary_status_code
|
||||
elif 'replica' in path:
|
||||
status_code = replica_status_code
|
||||
elif 'read-only' in path:
|
||||
status_code = 200 if 200 in (primary_status_code, standby_leader_status_code) else replica_status_code
|
||||
elif 'health' in path:
|
||||
status_code = 200 if response.get('state') == 'running' else 503
|
||||
elif cluster: # dcs is available
|
||||
is_synchronous = cluster.is_synchronous_mode() and cluster.sync \
|
||||
and cluster.sync.sync_standby == patroni.postgresql.name
|
||||
if path in ('/sync', '/synchronous') and is_synchronous:
|
||||
status_code = replica_status_code
|
||||
elif path in ('/async', '/asynchronous') and not is_synchronous:
|
||||
status_code = replica_status_code
|
||||
|
||||
if write_status_code_only: # when haproxy sends OPTIONS request it reads only status code and nothing more
|
||||
message = self.responses[status_code][0]
|
||||
self.wfile.write('{0} {1} {2}\r\n'.format(self.protocol_version, status_code, message).encode('utf-8'))
|
||||
self.wfile.write('{0} {1} {2}\r\n\r\n'.format(self.protocol_version, status_code, message).encode('utf-8'))
|
||||
else:
|
||||
self._write_status_response(status_code, response)
|
||||
|
||||
time_end = time.time()
|
||||
self.log_message('%s %s %s latency: %s ms', request_type, path,
|
||||
status_code, (time_end - time_start) * 1000)
|
||||
|
||||
def do_OPTIONS(self):
|
||||
self.do_GET(write_status_code_only=True)
|
||||
|
||||
@@ -110,6 +142,14 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
response = self.get_postgresql_status(True)
|
||||
self._write_status_response(200, response)
|
||||
|
||||
def do_GET_cluster(self):
|
||||
cluster = self.server.patroni.dcs.get_cluster(True)
|
||||
self._write_json_response(200, cluster_as_json(cluster))
|
||||
|
||||
def do_GET_history(self):
|
||||
cluster = self.server.patroni.dcs.cluster or self.server.patroni.dcs.get_cluster()
|
||||
self._write_json_response(200, cluster.history and cluster.history.lines or [])
|
||||
|
||||
def do_GET_config(self):
|
||||
cluster = self.server.patroni.dcs.cluster or self.server.patroni.dcs.get_cluster()
|
||||
if cluster.config:
|
||||
@@ -157,18 +197,8 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
|
||||
@check_auth
|
||||
def do_POST_reload(self):
|
||||
try:
|
||||
if self.server.patroni.config.reload_local_configuration(True):
|
||||
status_code = 202
|
||||
response = 'reload scheduled'
|
||||
self.server.patroni.sighup_handler()
|
||||
else:
|
||||
status_code = 200
|
||||
response = 'nothing changed'
|
||||
except Exception as e:
|
||||
status_code = 500
|
||||
response = str(e)
|
||||
self._write_response(status_code, response)
|
||||
self.server.patroni.sighup_handler()
|
||||
self._write_response(202, 'reload scheduled')
|
||||
|
||||
@staticmethod
|
||||
def parse_schedule(schedule, action):
|
||||
@@ -219,9 +249,11 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
data = "PostgreSQL role should be either master or replica"
|
||||
break
|
||||
elif k == 'postgres_version':
|
||||
if not is_valid_pg_version(request[k]):
|
||||
try:
|
||||
postgres_version_to_int(request[k])
|
||||
except PostgresException as e:
|
||||
status_code = 400
|
||||
data = "PostgreSQL version should be in the first.major.minor format"
|
||||
data = e.value
|
||||
break
|
||||
elif k == 'timeout':
|
||||
request[k] = parse_int(request[k], 's')
|
||||
@@ -260,9 +292,30 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
code = 404
|
||||
self._write_response(code, data)
|
||||
|
||||
@check_auth
|
||||
def do_DELETE_switchover(self):
|
||||
failover = self.server.patroni.dcs.get_cluster().failover
|
||||
if failover and failover.scheduled_at:
|
||||
if not self.server.patroni.dcs.manual_failover('', '', index=failover.index):
|
||||
return self.send_error(409)
|
||||
else:
|
||||
data = "scheduled switchover deleted"
|
||||
code = 200
|
||||
else:
|
||||
data = "no switchover is scheduled"
|
||||
code = 404
|
||||
self._write_response(code, data)
|
||||
|
||||
@check_auth
|
||||
def do_POST_reinitialize(self):
|
||||
data = self.server.patroni.ha.reinitialize()
|
||||
request = self._read_json_content(body_is_optional=True)
|
||||
|
||||
if request:
|
||||
logger.debug('received reinitialize request: %s', request)
|
||||
|
||||
force = isinstance(request, dict) and parse_bool(request.get('force')) or False
|
||||
|
||||
data = self.server.patroni.ha.reinitialize(force)
|
||||
if data is None:
|
||||
status_code = 200
|
||||
data = 'reinitialize started'
|
||||
@@ -270,43 +323,50 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
status_code = 503
|
||||
self._write_response(status_code, data)
|
||||
|
||||
def poll_failover_result(self, leader, candidate):
|
||||
def poll_failover_result(self, leader, candidate, action):
|
||||
timeout = max(10, self.server.patroni.dcs.loop_wait)
|
||||
for _ in range(0, timeout*2):
|
||||
time.sleep(1)
|
||||
try:
|
||||
cluster = self.server.patroni.dcs.get_cluster()
|
||||
if cluster.leader and cluster.leader.name != leader:
|
||||
if not cluster.is_unlocked() and cluster.leader.name != leader:
|
||||
if not candidate or candidate == cluster.leader.name:
|
||||
return 200, 'Successfully failed over to "{0}"'.format(cluster.leader.name)
|
||||
return 200, 'Successfully {0}ed over to "{1}"'.format(action[:-4], cluster.leader.name)
|
||||
else:
|
||||
return 200, 'Failed over to "{0}" instead of "{1}"'.format(cluster.leader.name, candidate)
|
||||
return 200, '{0}ed over to "{1}" instead of "{2}"'.format(action[:-4].title(),
|
||||
cluster.leader.name, candidate)
|
||||
if not cluster.failover:
|
||||
return 503, 'Failover failed'
|
||||
return 503, action.title() + ' failed'
|
||||
except Exception as e:
|
||||
logger.debug('Exception occured during polling failover result: %s', e)
|
||||
return 503, 'Failover status unknown'
|
||||
logger.debug('Exception occured during polling %s result: %s', action, e)
|
||||
return 503, action.title() + ' status unknown'
|
||||
|
||||
def is_failover_possible(self, cluster, leader, candidate):
|
||||
def is_failover_possible(self, cluster, leader, candidate, action):
|
||||
if leader and (not cluster.leader or cluster.leader.name != leader):
|
||||
return 'leader name does not match'
|
||||
if candidate:
|
||||
if action == 'switchover' and cluster.is_synchronous_mode() and cluster.sync.sync_standby != candidate:
|
||||
return 'candidate name does not match with sync_standby'
|
||||
members = [m for m in cluster.members if m.name == candidate]
|
||||
if not members:
|
||||
return 'candidate does not exists'
|
||||
elif cluster.is_synchronous_mode():
|
||||
members = [m for m in cluster.members if m.name == cluster.sync.sync_standby]
|
||||
if not members:
|
||||
return action + ' is not possible: can not find sync_standby'
|
||||
else:
|
||||
members = [m for m in cluster.members if m.name != cluster.leader.name and m.api_url]
|
||||
if not members:
|
||||
return 'failover is not possible: cluster does not have members except leader'
|
||||
for _, reachable, _, _, tags in self.server.patroni.ha.fetch_nodes_statuses(members):
|
||||
if reachable and not tags.get('nofailover', False):
|
||||
return action + ' is not possible: cluster does not have members except leader'
|
||||
for st in self.server.patroni.ha.fetch_nodes_statuses(members):
|
||||
if st.failover_limitation() is None:
|
||||
return None
|
||||
return 'failover is not possible: no good candidates have been found'
|
||||
return action + ' is not possible: no good candidates have been found'
|
||||
|
||||
@check_auth
|
||||
def do_POST_failover(self):
|
||||
def do_POST_failover(self, action='failover'):
|
||||
request = self._read_json_content()
|
||||
status_code = 500
|
||||
(status_code, data) = (400, '')
|
||||
if not request:
|
||||
return
|
||||
|
||||
@@ -315,39 +375,47 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
scheduled_at = request.get('scheduled_at')
|
||||
cluster = self.server.patroni.dcs.get_cluster()
|
||||
|
||||
if scheduled_at and cluster.is_paused():
|
||||
self._write_response(status_code, "Can't schedule failover in the paused state")
|
||||
logger.info("received %s request with leader=%s candidate=%s scheduled_at=%s",
|
||||
action, leader, candidate, scheduled_at)
|
||||
|
||||
logger.info("received failover request with leader=%s candidate=%s scheduled_at=%s",
|
||||
leader, candidate, scheduled_at)
|
||||
if action == 'failover' and not candidate:
|
||||
data = 'Failover could be performed only to a specific candidate'
|
||||
elif action == 'switchover' and not leader:
|
||||
data = 'Switchover could be performed only from a specific leader'
|
||||
|
||||
data = ''
|
||||
if leader or candidate:
|
||||
if scheduled_at:
|
||||
(_, data, scheduled_at) = self.parse_schedule(scheduled_at, "failover")
|
||||
if _:
|
||||
status_code = _
|
||||
elif self.server.patroni.dcs.manual_failover(leader, candidate, scheduled_at=scheduled_at):
|
||||
self.server.patroni.ha.wakeup()
|
||||
data = 'Failover scheduled'
|
||||
if not data and scheduled_at:
|
||||
if not leader:
|
||||
data = 'Scheduled {0} is possible only from a specific leader'.format(action)
|
||||
if not data and cluster.is_paused():
|
||||
data = "Can't schedule {0} in the paused state".format(action)
|
||||
if not data:
|
||||
(status_code, data, scheduled_at) = self.parse_schedule(scheduled_at, action)
|
||||
|
||||
if not data and cluster.is_paused() and not candidate:
|
||||
data = action.title() + ' is possible only to a specific candidate in a paused state'
|
||||
|
||||
if not data and not scheduled_at:
|
||||
data = self.is_failover_possible(cluster, leader, candidate, action)
|
||||
if data:
|
||||
status_code = 412
|
||||
|
||||
if not data:
|
||||
if self.server.patroni.dcs.manual_failover(leader, candidate, scheduled_at=scheduled_at):
|
||||
self.server.patroni.ha.wakeup()
|
||||
if scheduled_at:
|
||||
data = action.title() + ' scheduled'
|
||||
status_code = 202
|
||||
else:
|
||||
data = 'failed to write failover key into DCS'
|
||||
status_code = 503
|
||||
status_code, data = self.poll_failover_result(cluster.leader and cluster.leader.name,
|
||||
candidate, action)
|
||||
else:
|
||||
data = self.is_failover_possible(cluster, leader, candidate)
|
||||
if not data:
|
||||
if self.server.patroni.dcs.manual_failover(leader, candidate):
|
||||
self.server.patroni.ha.wakeup()
|
||||
status_code, data = self.poll_failover_result(cluster.leader and cluster.leader.name, candidate)
|
||||
else:
|
||||
data = 'failed to write failover key into DCS'
|
||||
status_code = 503
|
||||
else:
|
||||
status_code = 400
|
||||
data = 'No values given for required parameters leader and candidate'
|
||||
data = 'failed to write {0} key into DCS'.format(action)
|
||||
status_code = 503
|
||||
self._write_response(status_code, data)
|
||||
|
||||
def do_POST_switchover(self):
|
||||
self.do_POST_failover(action='switchover')
|
||||
|
||||
def parse_request(self):
|
||||
"""Override parse_request method to enrich basic functionality of `BaseHTTPRequestHandler` class
|
||||
|
||||
@@ -373,60 +441,69 @@ class RestApiHandler(BaseHTTPRequestHandler):
|
||||
return retry(self.server.query, sql, *params)
|
||||
|
||||
def get_postgresql_status(self, retry=False):
|
||||
postgresql = self.server.patroni.postgresql
|
||||
try:
|
||||
row = self.query("""WITH replication_info AS (
|
||||
SELECT usename, application_name, client_addr, state, sync_state, sync_priority
|
||||
FROM pg_stat_replication
|
||||
)
|
||||
SELECT to_char(pg_postmaster_start_time(), 'YYYY-MM-DD HH24:MI:SS.MS TZ'),
|
||||
pg_is_in_recovery(),
|
||||
CASE WHEN pg_is_in_recovery()
|
||||
THEN 0
|
||||
ELSE pg_xlog_location_diff(pg_current_xlog_location(), '0/0')::bigint
|
||||
END,
|
||||
pg_xlog_location_diff(COALESCE(pg_last_xlog_receive_location(),
|
||||
pg_last_xlog_replay_location()), '0/0')::bigint,
|
||||
pg_xlog_location_diff(pg_last_xlog_replay_location(), '0/0')::bigint,
|
||||
to_char(pg_last_xact_replay_timestamp(), 'YYYY-MM-DD HH24:MI:SS.MS TZ'),
|
||||
pg_is_in_recovery() AND pg_is_xlog_replay_paused(),
|
||||
(SELECT array_to_json(array_agg(row_to_json(ri))) FROM replication_info ri)""",
|
||||
retry=retry)[0]
|
||||
cluster = self.server.patroni.dcs.cluster
|
||||
|
||||
if postgresql.state not in ('running', 'restarting', 'starting'):
|
||||
raise RetryFailedError('')
|
||||
stmt = ("SELECT " + postgresql.POSTMASTER_START_TIME + ", " + postgresql.TL_LSN + ","
|
||||
" pg_catalog.to_char(pg_catalog.pg_last_xact_replay_timestamp(), 'YYYY-MM-DD HH24:MI:SS.MS TZ'),"
|
||||
" pg_catalog.array_to_json(pg_catalog.array_agg(pg_catalog.row_to_json(ri))) "
|
||||
"FROM (SELECT (SELECT rolname FROM pg_authid WHERE oid = usesysid) AS usename,"
|
||||
" application_name, client_addr, w.state, sync_state, sync_priority"
|
||||
" FROM pg_catalog.pg_stat_get_wal_senders() w, pg_catalog.pg_stat_get_activity(pid)) AS ri")
|
||||
|
||||
row = self.query(stmt.format(postgresql.wal_name, postgresql.lsn_name), retry=retry)[0]
|
||||
|
||||
result = {
|
||||
'state': self.server.patroni.postgresql.state,
|
||||
'state': postgresql.state,
|
||||
'postmaster_start_time': row[0],
|
||||
'role': 'replica' if row[1] else 'master',
|
||||
'server_version': self.server.patroni.postgresql.server_version,
|
||||
'role': 'replica' if row[1] == 0 else 'master',
|
||||
'server_version': postgresql.server_version,
|
||||
'cluster_unlocked': bool(not cluster or cluster.is_unlocked()),
|
||||
'xlog': ({
|
||||
'received_location': row[3],
|
||||
'replayed_location': row[4],
|
||||
'replayed_timestamp': row[5],
|
||||
'paused': row[6]} if row[1] else {
|
||||
'received_location': row[4] or row[3],
|
||||
'replayed_location': row[3],
|
||||
'replayed_timestamp': row[6],
|
||||
'paused': row[5]} if row[1] == 0 else {
|
||||
'location': row[2]
|
||||
})
|
||||
}
|
||||
|
||||
if result['role'] == 'replica' and self.server.patroni.ha.is_standby_cluster():
|
||||
result['role'] = postgresql.role
|
||||
|
||||
if row[1] > 0:
|
||||
result['timeline'] = row[1]
|
||||
else:
|
||||
leader_timeline = None if not cluster or cluster.is_unlocked() else cluster.leader.timeline
|
||||
result['timeline'] = postgresql.replica_cached_timeline(leader_timeline)
|
||||
|
||||
if row[7]:
|
||||
result['replication'] = row[7]
|
||||
|
||||
return result
|
||||
except (psycopg2.Error, RetryFailedError, PostgresConnectionException):
|
||||
state = self.server.patroni.postgresql.state
|
||||
state = postgresql.state
|
||||
if state == 'running':
|
||||
logger.exception('get_postgresql_status')
|
||||
state = 'unknown'
|
||||
return {'state': state, 'role': self.server.patroni.postgresql.role}
|
||||
return {'state': state, 'role': postgresql.role}
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
logger.debug("API thread: %s - - [%s] %s", self.client_address[0], self.log_date_time_string(), fmt % args)
|
||||
|
||||
|
||||
class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
|
||||
# On 3.7+ the `ThreadingMixIn` gathers all non-daemon worker threads in order to join on them at server close.
|
||||
daemon_threads = True # Make worker threads "fire and forget" to prevent a memory leak.
|
||||
|
||||
def __init__(self, patroni, config):
|
||||
self.patroni = patroni
|
||||
self.__initialize(config)
|
||||
self.__set_config_parameters(config)
|
||||
self.__listen = None
|
||||
self.__ssl_options = None
|
||||
self.reload_config(config)
|
||||
self.daemon = True
|
||||
|
||||
def query(self, sql, *params):
|
||||
@@ -442,8 +519,10 @@ class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
|
||||
|
||||
@staticmethod
|
||||
def _set_fd_cloexec(fd):
|
||||
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
|
||||
fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
|
||||
if os.name != 'nt':
|
||||
import fcntl
|
||||
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
|
||||
fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
|
||||
|
||||
def check_basic_auth_key(self, key):
|
||||
return self.__auth_key == key
|
||||
@@ -455,38 +534,119 @@ class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
|
||||
if not auth_header.startswith('Basic ') or not self.check_basic_auth_key(auth_header[6:]):
|
||||
return 'not authenticated'
|
||||
|
||||
def check_auth(self, rh):
|
||||
if not hasattr(rh.request, 'getpeercert') or not rh.request.getpeercert(): # valid client cert isn't present
|
||||
if self.__protocol == 'https' and self.__ssl_options.get('verify_client') in ('required', 'optional'):
|
||||
return rh._write_response(403, 'client certificate required')
|
||||
|
||||
reason = self.check_auth_header(rh.headers.get('Authorization'))
|
||||
if reason:
|
||||
headers = {'WWW-Authenticate': 'Basic realm="' + self.patroni.__class__.__name__ + '"'}
|
||||
return rh._write_response(401, reason, headers=headers)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def __get_ssl_options(config):
|
||||
return {option: config[option] for option in ['certfile', 'keyfile'] if option in config}
|
||||
def __has_dual_stack():
|
||||
if hasattr(socket, 'AF_INET6') and hasattr(socket, 'IPPROTO_IPV6') and hasattr(socket, 'IPV6_V6ONLY'):
|
||||
sock = None
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
|
||||
return True
|
||||
except socket.error as e:
|
||||
logger.debug('Error when working with ipv6 socket: %s', e)
|
||||
finally:
|
||||
if sock:
|
||||
sock.close()
|
||||
return False
|
||||
|
||||
def __set_connection_string(self, connect_address):
|
||||
self.connection_string = '{0}://{1}/patroni'.format(self.__protocol, connect_address or self.__listen)
|
||||
def __httpserver_init(self, host, port):
|
||||
dual_stack = self.__has_dual_stack()
|
||||
if host in ('', '*'):
|
||||
host = None
|
||||
|
||||
def __set_config_parameters(self, config):
|
||||
self.__auth_key = base64.b64encode(config['auth'].encode('utf-8')).decode('utf-8') if 'auth' in config else None
|
||||
self.__set_connection_string(config.get('connect_address'))
|
||||
info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
|
||||
# in case dual stack is not supported we want IPv4 to be preferred over IPv6
|
||||
info.sort(key=lambda x: x[0] == socket.AF_INET, reverse=not dual_stack)
|
||||
|
||||
def __initialize(self, config):
|
||||
self.__ssl_options = self.__get_ssl_options(config)
|
||||
self.__listen = config['listen']
|
||||
host, port = config['listen'].split(':')
|
||||
HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
|
||||
self.address_family = info[0][0]
|
||||
try:
|
||||
HTTPServer.__init__(self, info[0][-1][:2], RestApiHandler)
|
||||
except socket.error:
|
||||
logger.error(
|
||||
"Couldn't start a service on '%s:%s', please check your `restapi.listen` configuration", host, port)
|
||||
raise
|
||||
|
||||
def __initialize(self, listen, ssl_options):
|
||||
try:
|
||||
host, port = split_host_port(listen, None)
|
||||
except Exception:
|
||||
raise ValueError('Invalid "restapi" config: expected <HOST>:<PORT> for "listen", but got "{0}"'
|
||||
.format(listen))
|
||||
|
||||
reloading_config = self.__listen is not None # changing config in runtime
|
||||
if reloading_config:
|
||||
self.shutdown()
|
||||
|
||||
self.__listen = listen
|
||||
self.__ssl_options = ssl_options
|
||||
|
||||
self.__httpserver_init(host, port)
|
||||
Thread.__init__(self, target=self.serve_forever)
|
||||
self._set_fd_cloexec(self.socket)
|
||||
|
||||
self.__protocol = 'http'
|
||||
|
||||
# wrap socket with ssl if 'certfile' is defined in a config.yaml
|
||||
# Sometime it's also needed to pass reference to a 'keyfile'.
|
||||
if self.__ssl_options.get('certfile'):
|
||||
self.__protocol = 'https' if ssl_options.get('certfile') else 'http'
|
||||
if self.__protocol == 'https':
|
||||
import ssl
|
||||
self.socket = ssl.wrap_socket(self.socket, server_side=True, **self.__ssl_options)
|
||||
self.__protocol = 'https'
|
||||
self.__set_connection_string(config.get('connect_address'))
|
||||
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH, cafile=ssl_options.get('cafile'))
|
||||
ctx.load_cert_chain(certfile=ssl_options['certfile'], keyfile=ssl_options.get('keyfile'))
|
||||
verify_client = ssl_options.get('verify_client')
|
||||
if verify_client:
|
||||
modes = {'none': ssl.CERT_NONE, 'optional': ssl.CERT_OPTIONAL, 'required': ssl.CERT_REQUIRED}
|
||||
if verify_client in modes:
|
||||
ctx.verify_mode = modes[verify_client]
|
||||
else:
|
||||
logger.error('Bad value in the "restapi.verify_client": %s', verify_client)
|
||||
self.socket = ctx.wrap_socket(self.socket, server_side=True)
|
||||
if reloading_config:
|
||||
self.start()
|
||||
|
||||
def process_request_thread(self, request, client_address):
|
||||
if isinstance(request, tuple):
|
||||
sock, newsock = request
|
||||
try:
|
||||
request = sock.context.wrap_socket(newsock, do_handshake_on_connect=sock.do_handshake_on_connect,
|
||||
suppress_ragged_eofs=sock.suppress_ragged_eofs, server_side=True)
|
||||
except socket.error:
|
||||
return
|
||||
super(RestApiServer, self).process_request_thread(request, client_address)
|
||||
|
||||
def get_request(self):
|
||||
sock = self.socket
|
||||
newsock, addr = socket.socket.accept(sock)
|
||||
if hasattr(sock, 'context'): # SSLSocket, we want to do the deferred handshake from a thread
|
||||
newsock = (sock, newsock)
|
||||
return newsock, addr
|
||||
|
||||
def reload_config(self, config):
|
||||
self.__set_config_parameters(config)
|
||||
if self.__listen != config['listen'] or self.__ssl_options != self.__get_ssl_options(config):
|
||||
self.shutdown()
|
||||
self.__initialize(config)
|
||||
self.start()
|
||||
if 'listen' not in config: # changing config in runtime
|
||||
raise ValueError('Can not find "restapi.listen" config')
|
||||
|
||||
ssl_options = {n: config[n] for n in ('certfile', 'keyfile', 'cafile') if n in config}
|
||||
|
||||
if isinstance(config.get('verify_client'), six.string_types):
|
||||
ssl_options['verify_client'] = config['verify_client'].lower()
|
||||
|
||||
if self.__listen != config['listen'] or self.__ssl_options != ssl_options:
|
||||
self.__initialize(config['listen'], ssl_options)
|
||||
|
||||
self.__auth_key = base64.b64encode(config['auth'].encode('utf-8')).decode('utf-8') if 'auth' in config else None
|
||||
self.connection_string = uri(self.__protocol, config.get('connect_address') or self.__listen, 'patroni')
|
||||
|
||||
@staticmethod
|
||||
def handle_error(request, client_address):
|
||||
address, port = client_address
|
||||
logger.warning('Exception happened during processing of request from {}:{}'.format(address, port))
|
||||
logger.warning(traceback.format_exc())
|
||||
|
||||
@@ -1,26 +1,78 @@
|
||||
import logging
|
||||
from threading import RLock, Thread
|
||||
from threading import Event, Lock, RLock, Thread
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CriticalTask(object):
|
||||
"""Represents a critical task in a background process that we either need to cancel or get the result of.
|
||||
|
||||
Fields of this object may be accessed only when holding a lock on it. To perform the critical task the background
|
||||
thread must, while holding lock on this object, check `is_cancelled` flag, run the task and mark the task as
|
||||
complete using `complete()`.
|
||||
|
||||
The main thread must hold async lock to prevent the task from completing, hold lock on critical task object,
|
||||
call cancel. If the task has completed `cancel()` will return False and `result` field will contain the result of
|
||||
the task. When cancel returns True it is guaranteed that the background task will notice the `is_cancelled` flag.
|
||||
"""
|
||||
def __init__(self):
|
||||
self._lock = Lock()
|
||||
self.is_cancelled = False
|
||||
self.result = None
|
||||
|
||||
def reset(self):
|
||||
"""Must be called every time the background task is finished.
|
||||
|
||||
Must be called from async thread. Caller must hold lock on async executor when calling."""
|
||||
self.is_cancelled = False
|
||||
self.result = None
|
||||
|
||||
def cancel(self):
|
||||
"""Tries to cancel the task, returns True if the task has already run.
|
||||
|
||||
Caller must hold lock on async executor and the task when calling."""
|
||||
if self.result is not None:
|
||||
return False
|
||||
self.is_cancelled = True
|
||||
return True
|
||||
|
||||
def complete(self, result):
|
||||
"""Mark task as completed along with a result.
|
||||
|
||||
Must be called from async thread. Caller must hold lock on task when calling."""
|
||||
self.result = result
|
||||
|
||||
def __enter__(self):
|
||||
self._lock.acquire()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self._lock.release()
|
||||
|
||||
|
||||
class AsyncExecutor(object):
|
||||
|
||||
def __init__(self, ha_wakeup):
|
||||
def __init__(self, cancellable, ha_wakeup):
|
||||
self._cancellable = cancellable
|
||||
self._ha_wakeup = ha_wakeup
|
||||
self._thread_lock = RLock()
|
||||
self._scheduled_action = None
|
||||
self._scheduled_action_lock = RLock()
|
||||
self._is_cancelled = False
|
||||
self._finish_event = Event()
|
||||
self.critical_task = CriticalTask()
|
||||
|
||||
@property
|
||||
def busy(self):
|
||||
return self.scheduled_action is not None
|
||||
|
||||
def schedule(self, action, immediately=False):
|
||||
def schedule(self, action):
|
||||
with self._scheduled_action_lock:
|
||||
if self._scheduled_action is not None:
|
||||
return self._scheduled_action
|
||||
self._scheduled_action = action
|
||||
self._is_cancelled = False
|
||||
self._finish_event.set()
|
||||
return None
|
||||
|
||||
@property
|
||||
@@ -35,20 +87,49 @@ class AsyncExecutor(object):
|
||||
def run(self, func, args=()):
|
||||
wakeup = False
|
||||
try:
|
||||
with self:
|
||||
if self._is_cancelled:
|
||||
return
|
||||
self._finish_event.clear()
|
||||
|
||||
self._cancellable.reset_is_cancelled()
|
||||
# if the func returned something (not None) - wake up main HA loop
|
||||
wakeup = func(*args) if args else func()
|
||||
return wakeup
|
||||
except:
|
||||
except Exception:
|
||||
logger.exception('Exception during execution of long running task %s', self.scheduled_action)
|
||||
finally:
|
||||
with self:
|
||||
self.reset_scheduled_action()
|
||||
self._finish_event.set()
|
||||
with self.critical_task:
|
||||
self.critical_task.reset()
|
||||
if wakeup is not None:
|
||||
self._ha_wakeup()
|
||||
|
||||
def run_async(self, func, args=()):
|
||||
Thread(target=self.run, args=(func, args)).start()
|
||||
|
||||
def try_run_async(self, action, func, args=()):
|
||||
prev = self.schedule(action)
|
||||
if prev is None:
|
||||
return self.run_async(func, args)
|
||||
return 'Failed to run {0}, {1} is already in progress'.format(action, prev)
|
||||
|
||||
def cancel(self):
|
||||
with self:
|
||||
with self._scheduled_action_lock:
|
||||
if self._scheduled_action is None:
|
||||
return
|
||||
logger.warning('Cancelling long running task %s', self._scheduled_action)
|
||||
self._is_cancelled = True
|
||||
|
||||
self._cancellable.cancel()
|
||||
self._finish_event.wait()
|
||||
|
||||
with self:
|
||||
self.reset_scheduled_action()
|
||||
|
||||
def __enter__(self):
|
||||
self._thread_lock.acquire()
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import logging
|
||||
import subprocess
|
||||
from threading import Event, Lock, Thread
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CallbackExecutor(Thread):
|
||||
|
||||
def __init__(self):
|
||||
super(CallbackExecutor, self).__init__()
|
||||
self.daemon = True
|
||||
self._lock = Lock()
|
||||
self._cmd = None
|
||||
self._process = None
|
||||
self._callback_event = Event()
|
||||
self.start()
|
||||
|
||||
def call(self, cmd):
|
||||
with self._lock:
|
||||
if self._process and self._process.poll() is None:
|
||||
self._process.kill()
|
||||
logger.warning('Killed the old callback process because it was still running: %s', self._cmd)
|
||||
self._cmd = cmd
|
||||
self._callback_event.set()
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
self._callback_event.wait()
|
||||
self._callback_event.clear()
|
||||
with self._lock:
|
||||
try:
|
||||
self._process = subprocess.Popen(self._cmd, close_fds=True)
|
||||
except Exception:
|
||||
logger.exception('Failed to execute %s', self._cmd)
|
||||
continue
|
||||
self._process.wait()
|
||||
+144
-60
@@ -1,18 +1,37 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import tempfile
|
||||
import yaml
|
||||
|
||||
from collections import defaultdict
|
||||
from copy import deepcopy
|
||||
from patroni import PATRONI_ENV_PREFIX
|
||||
from patroni.exceptions import ConfigParseError
|
||||
from patroni.dcs import ClusterConfig
|
||||
from patroni.postgresql import Postgresql
|
||||
from patroni.utils import deep_compare, parse_int, patch_config
|
||||
from patroni.postgresql.config import CaseInsensitiveDict, ConfigHandler
|
||||
from patroni.utils import deep_compare, parse_bool, parse_int, patch_config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_AUTH_ALLOWED_PARAMETERS = (
|
||||
'username',
|
||||
'password',
|
||||
'sslmode',
|
||||
'sslcert',
|
||||
'sslkey',
|
||||
'sslrootcert',
|
||||
'sslcrl',
|
||||
'gssencmode',
|
||||
'channel_binding'
|
||||
)
|
||||
|
||||
|
||||
def default_validator(conf):
|
||||
if not conf:
|
||||
return "Config is empty."
|
||||
|
||||
|
||||
class Config(object):
|
||||
"""
|
||||
@@ -34,43 +53,56 @@ class Config(object):
|
||||
to work with it as with the old `config` object.
|
||||
"""
|
||||
|
||||
PATRONI_ENV_PREFIX = 'PATRONI_'
|
||||
PATRONI_CONFIG_VARIABLE = PATRONI_ENV_PREFIX + 'CONFIGURATION'
|
||||
|
||||
__CACHE_FILENAME = 'patroni.dynamic.json'
|
||||
__DEFAULT_CONFIG = {
|
||||
'ttl': 30, 'loop_wait': 10, 'retry_timeout': 10,
|
||||
'maximum_lag_on_failover': 1048576,
|
||||
'check_timeline': False,
|
||||
'master_start_timeout': 300,
|
||||
'master_stop_timeout': 0,
|
||||
'synchronous_mode': 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': {
|
||||
'bin_dir': '',
|
||||
'use_slots': True,
|
||||
'parameters': {p: v[0] for p, v in Postgresql.CMDLINE_OPTIONS.items()}
|
||||
'parameters': CaseInsensitiveDict({p: v[0] for p, v in ConfigHandler.CMDLINE_OPTIONS.items()})
|
||||
},
|
||||
'watchdog': {
|
||||
'mode': 'automatic',
|
||||
}
|
||||
}
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, configfile, validator=default_validator):
|
||||
self._modify_index = -1
|
||||
self._dynamic_configuration = {}
|
||||
|
||||
self.__environment_configuration = self._build_environment_configuration()
|
||||
|
||||
# Patroni reads the configuration from the command-line argument if it exists, otherwise from the environment
|
||||
self._config_file = len(sys.argv) >= 2 and os.path.isfile(sys.argv[1]) and sys.argv[1]
|
||||
self._config_file = configfile and os.path.isfile(configfile) and configfile
|
||||
if self._config_file:
|
||||
self._local_configuration = self._load_config_file()
|
||||
else:
|
||||
config_env = os.environ.pop(self.PATRONI_CONFIG_VARIABLE, None)
|
||||
self._local_configuration = config_env and yaml.safe_load(config_env) or self.__environment_configuration
|
||||
if not self._local_configuration:
|
||||
print('Usage: {0} config.yml'.format(sys.argv[0]))
|
||||
print('\tPatroni may also read the configuration from the {0} environment variable'.
|
||||
format(self.PATRONI_CONFIG_VARIABLE))
|
||||
sys.exit(1)
|
||||
if validator:
|
||||
error = validator(self._local_configuration)
|
||||
if error:
|
||||
raise ConfigParseError(error)
|
||||
|
||||
self.__effective_configuration = self._build_effective_configuration({}, self._local_configuration)
|
||||
self._data_dir = self.__effective_configuration['postgresql']['data_dir']
|
||||
self._data_dir = self.__effective_configuration.get('postgresql', {}).get('data_dir', "")
|
||||
self._cache_file = os.path.join(self._data_dir, self.__CACHE_FILENAME)
|
||||
self._load_cache()
|
||||
self._cache_needs_saving = False
|
||||
@@ -83,6 +115,9 @@ class Config(object):
|
||||
def dynamic_configuration(self):
|
||||
return deepcopy(self._dynamic_configuration)
|
||||
|
||||
def check_mode(self, mode):
|
||||
return bool(parse_bool(self._dynamic_configuration.get(mode)))
|
||||
|
||||
def _load_config_file(self):
|
||||
"""Loads config.yaml from filesystem and applies some values which were set via ENV"""
|
||||
with open(self._config_file) as f:
|
||||
@@ -106,7 +141,7 @@ class Config(object):
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
fd = None
|
||||
json.dump(self.dynamic_configuration, f)
|
||||
tmpfile = os.rename(tmpfile, self._cache_file)
|
||||
tmpfile = shutil.move(tmpfile, self._cache_file)
|
||||
self._cache_needs_saving = False
|
||||
except Exception:
|
||||
logger.exception('Exception when saving file: %s', self._cache_file)
|
||||
@@ -139,29 +174,25 @@ class Config(object):
|
||||
except Exception:
|
||||
logger.exception('Exception when setting dynamic_configuration')
|
||||
|
||||
def reload_local_configuration(self, dry_run=False):
|
||||
def reload_local_configuration(self):
|
||||
if self.config_file:
|
||||
try:
|
||||
configuration = self._load_config_file()
|
||||
if not deep_compare(self._local_configuration, configuration):
|
||||
new_configuration = self._build_effective_configuration(self._dynamic_configuration, configuration)
|
||||
if dry_run:
|
||||
return not deep_compare(new_configuration, self.__effective_configuration)
|
||||
self._local_configuration = configuration
|
||||
self.__effective_configuration = new_configuration
|
||||
return True
|
||||
else:
|
||||
logger.info('No local configuration items changed.')
|
||||
except Exception:
|
||||
logger.exception('Exception when reloading local configuration from %s', self.config_file)
|
||||
if dry_run:
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _process_postgresql_parameters(parameters, is_local=False):
|
||||
ret = {}
|
||||
for name, value in (parameters or {}).items():
|
||||
if name not in Postgresql.CMDLINE_OPTIONS or not is_local and Postgresql.CMDLINE_OPTIONS[name][1](value):
|
||||
ret[name] = value
|
||||
return ret
|
||||
return {name: value for name, value in (parameters or {}).items()
|
||||
if name not in ConfigHandler.CMDLINE_OPTIONS or
|
||||
not is_local and ConfigHandler.CMDLINE_OPTIONS[name][1](value)}
|
||||
|
||||
def _safe_copy_dynamic_configuration(self, dynamic_configuration):
|
||||
config = deepcopy(self.__DEFAULT_CONFIG)
|
||||
@@ -173,8 +204,12 @@ class Config(object):
|
||||
config['postgresql'][name].update(self._process_postgresql_parameters(value))
|
||||
elif name not in ('connect_address', 'listen', 'data_dir', 'pgpass', 'authentication'):
|
||||
config['postgresql'][name] = deepcopy(value)
|
||||
elif name == 'standby_cluster':
|
||||
for name, value in (value or {}).items():
|
||||
if name in self.__DEFAULT_CONFIG['standby_cluster']:
|
||||
config['standby_cluster'][name] = deepcopy(value)
|
||||
elif name in config: # only variables present in __DEFAULT_CONFIG allowed to be overriden from DCS
|
||||
if name == 'synchronous_mode':
|
||||
if name in ('synchronous_mode', 'synchronous_mode_strict'):
|
||||
config[name] = value
|
||||
else:
|
||||
config[name] = int(value)
|
||||
@@ -185,25 +220,52 @@ class Config(object):
|
||||
ret = defaultdict(dict)
|
||||
|
||||
def _popenv(name):
|
||||
return os.environ.pop(Config.PATRONI_ENV_PREFIX + name.upper(), None)
|
||||
return os.environ.pop(PATRONI_ENV_PREFIX + name.upper(), None)
|
||||
|
||||
for param in ('name', 'namespace', 'scope'):
|
||||
value = _popenv(param)
|
||||
if value:
|
||||
ret[param] = value
|
||||
|
||||
def _fix_log_env(name, oldname):
|
||||
value = _popenv(oldname)
|
||||
name = PATRONI_ENV_PREFIX + 'LOG_' + name.upper()
|
||||
if value and name not in os.environ:
|
||||
os.environ[name] = value
|
||||
|
||||
for name, oldname in (('level', 'loglevel'), ('format', 'logformat'), ('dateformat', 'log_datefmt')):
|
||||
_fix_log_env(name, oldname)
|
||||
|
||||
def _set_section_values(section, params):
|
||||
for param in params:
|
||||
value = _popenv(section + '_' + param)
|
||||
if value:
|
||||
ret[section][param] = value
|
||||
|
||||
_set_section_values('restapi', ['listen', 'connect_address', 'certfile', 'keyfile'])
|
||||
_set_section_values('postgresql', ['listen', 'connect_address', 'data_dir', 'pgpass', 'bin_dir'])
|
||||
_set_section_values('restapi', ['listen', 'connect_address', 'certfile', 'keyfile', 'cafile', 'verify_client'])
|
||||
_set_section_values('ctl', ['insecure', 'cacert', 'certfile', 'keyfile'])
|
||||
_set_section_values('postgresql', ['listen', 'connect_address', 'config_dir', 'data_dir', 'pgpass', 'bin_dir'])
|
||||
_set_section_values('log', ['level', 'traceback_level', 'format', 'dateformat', 'max_queue_size',
|
||||
'dir', 'file_size', 'file_num', 'loggers'])
|
||||
|
||||
def _get_auth(name):
|
||||
def _parse_dict(value):
|
||||
if not value.strip().startswith('{'):
|
||||
value = '{{{0}}}'.format(value)
|
||||
try:
|
||||
return yaml.safe_load(value)
|
||||
except Exception:
|
||||
logger.exception('Exception when parsing dict %s', value)
|
||||
return None
|
||||
|
||||
value = ret.get('log', {}).pop('loggers', None)
|
||||
if value:
|
||||
value = _parse_dict(value)
|
||||
if value:
|
||||
ret['log']['loggers'] = value
|
||||
|
||||
def _get_auth(name, params=None):
|
||||
ret = {}
|
||||
for param in ('username', 'password'):
|
||||
for param in params or _AUTH_ALLOWED_PARAMETERS[:2]:
|
||||
value = _popenv(name + '_' + param)
|
||||
if value:
|
||||
ret[param] = value
|
||||
@@ -214,16 +276,14 @@ class Config(object):
|
||||
ret['restapi']['authentication'] = restapi_auth
|
||||
|
||||
authentication = {}
|
||||
for user_type in ('replication', 'superuser'):
|
||||
entry = _get_auth(user_type)
|
||||
for user_type in ('replication', 'superuser', 'rewind'):
|
||||
entry = _get_auth(user_type, _AUTH_ALLOWED_PARAMETERS)
|
||||
if entry:
|
||||
authentication[user_type] = entry
|
||||
|
||||
if authentication:
|
||||
ret['postgresql']['authentication'] = authentication
|
||||
|
||||
users = {}
|
||||
|
||||
def _parse_list(value):
|
||||
if not (value.strip().startswith('-') or '[' in value):
|
||||
value = '[{0}]'.format(value)
|
||||
@@ -234,29 +294,41 @@ class Config(object):
|
||||
return None
|
||||
|
||||
for param in list(os.environ.keys()):
|
||||
if param.startswith(Config.PATRONI_ENV_PREFIX):
|
||||
if param.startswith(PATRONI_ENV_PREFIX):
|
||||
# PATRONI_(ETCD|CONSUL|ZOOKEEPER|EXHIBITOR|...)_(HOSTS?|PORT|..)
|
||||
name, suffix = (param[8:].split('_', 1) + [''])[:2]
|
||||
if suffix in ('HOST', 'HOSTS', 'PORT', 'USE_PROXIES', 'PROTOCOL', 'SRV', 'URL', 'PROXY',
|
||||
'CACERT', 'CERT', 'KEY', 'VERIFY', 'TOKEN', 'CHECKS', 'DC', 'CONSISTENCY',
|
||||
'REGISTER_SERVICE', 'SERVICE_CHECK_INTERVAL', 'NAMESPACE', 'CONTEXT',
|
||||
'USE_ENDPOINTS', 'SCOPE_LABEL', 'ROLE_LABEL', 'POD_IP', 'PORTS', 'LABELS') and name:
|
||||
value = os.environ.pop(param)
|
||||
if suffix == 'PORT':
|
||||
value = value and parse_int(value)
|
||||
elif suffix in ('HOSTS', 'PORTS', 'CHECKS'):
|
||||
value = value and _parse_list(value)
|
||||
elif suffix == 'LABELS':
|
||||
value = _parse_dict(value)
|
||||
elif suffix in ('USE_PROXIES', 'REGISTER_SERVICE'):
|
||||
value = parse_bool(value)
|
||||
if value:
|
||||
ret[name.lower()][suffix.lower()] = value
|
||||
if 'etcd' in ret:
|
||||
ret['etcd'].update(_get_auth('etcd'))
|
||||
|
||||
users = {}
|
||||
for param in list(os.environ.keys()):
|
||||
if param.startswith(PATRONI_ENV_PREFIX):
|
||||
name, suffix = (param[8:].rsplit('_', 1) + [''])[:2]
|
||||
if name and suffix:
|
||||
# PATRONI_(ETCD|CONSUL|ZOOKEEPER|EXHIBITOR|...)_(HOSTS?|PORT|..)
|
||||
if suffix in ('HOST', 'HOSTS', 'PORT', 'SRV', 'URL', 'PROXY', 'CACERT', 'CERT', 'KEY') \
|
||||
and '_' not in name:
|
||||
value = os.environ.pop(param)
|
||||
if suffix == 'PORT':
|
||||
value = value and parse_int(value)
|
||||
elif suffix == 'HOSTS':
|
||||
value = value and _parse_list(value)
|
||||
if value:
|
||||
ret[name.lower()][suffix.lower()] = value
|
||||
# PATRONI_<username>_PASSWORD=<password>, PATRONI_<username>_OPTIONS=<option1,option2,...>
|
||||
# CREATE USER "<username>" WITH <OPTIONS> PASSWORD '<password>'
|
||||
elif suffix == 'PASSWORD':
|
||||
password = os.environ.pop(param)
|
||||
if password:
|
||||
users[name] = {'password': password}
|
||||
options = os.environ.pop(param[:-9] + '_OPTIONS', None)
|
||||
options = options and _parse_list(options)
|
||||
if options:
|
||||
users[name]['options'] = options
|
||||
# PATRONI_<username>_PASSWORD=<password>, PATRONI_<username>_OPTIONS=<option1,option2,...>
|
||||
# CREATE USER "<username>" WITH <OPTIONS> PASSWORD '<password>'
|
||||
if name and suffix == 'PASSWORD':
|
||||
password = os.environ.pop(param)
|
||||
if password:
|
||||
users[name] = {'password': password}
|
||||
options = os.environ.pop(param[:-9] + '_OPTIONS', None)
|
||||
options = options and _parse_list(options)
|
||||
if options:
|
||||
users[name]['options'] = options
|
||||
if users:
|
||||
ret['bootstrap']['users'] = users
|
||||
|
||||
@@ -271,11 +343,11 @@ class Config(object):
|
||||
config['postgresql'][name].update(self._process_postgresql_parameters(value, True))
|
||||
elif name != 'use_slots': # replication slots must be enabled/disabled globally
|
||||
config['postgresql'][name] = deepcopy(value)
|
||||
elif name not in config:
|
||||
elif name not in config or name in ['watchdog']:
|
||||
config[name] = deepcopy(value) if value else {}
|
||||
|
||||
# restapi server expects to get restapi.auth = 'username:password'
|
||||
if 'authentication' in config['restapi']:
|
||||
if 'restapi' in config and 'authentication' in config['restapi']:
|
||||
config['restapi']['auth'] = '{username}:{password}'.format(**config['restapi']['authentication'])
|
||||
|
||||
# special treatment for old config
|
||||
@@ -294,12 +366,24 @@ class Config(object):
|
||||
if 'superuser' not in pg_config['authentication'] and 'pg_rewind' in pg_config:
|
||||
pg_config['authentication']['superuser'] = pg_config['pg_rewind']
|
||||
|
||||
# handle setting additional connection parameters that may be available
|
||||
# in the configuration file, such as SSL connection parameters
|
||||
for name, value in pg_config['authentication'].items():
|
||||
pg_config['authentication'][name] = {n: v for n, v in value.items() if n in _AUTH_ALLOWED_PARAMETERS}
|
||||
|
||||
# no 'name' in config
|
||||
if 'name' not in config and 'name' in pg_config:
|
||||
config['name'] = pg_config['name']
|
||||
|
||||
pg_config.update({p: config[p] for p in ('name', 'scope', 'retry_timeout',
|
||||
'synchronous_mode', 'maximum_lag_on_failover') if p in config})
|
||||
updated_fields = (
|
||||
'name',
|
||||
'scope',
|
||||
'retry_timeout',
|
||||
'synchronous_mode',
|
||||
'synchronous_mode_strict',
|
||||
)
|
||||
|
||||
pg_config.update({p: config[p] for p in updated_fields if p in config})
|
||||
|
||||
return config
|
||||
|
||||
|
||||
+739
-227
File diff suppressed because it is too large
Load Diff
+336
-62
@@ -3,17 +3,41 @@ import dateutil
|
||||
import importlib
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import pkgutil
|
||||
import re
|
||||
import six
|
||||
import sys
|
||||
import time
|
||||
|
||||
from collections import namedtuple
|
||||
from collections import defaultdict, namedtuple
|
||||
from copy import deepcopy
|
||||
from patroni.exceptions import PatroniException
|
||||
from patroni.utils import parse_bool, uri
|
||||
from random import randint
|
||||
from six.moves.urllib_parse import urlparse, urlunparse, parse_qsl
|
||||
from threading import Event, Lock
|
||||
|
||||
slot_name_re = re.compile('^[a-z0-9_]{1,63}$')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def slot_name_from_member_name(member_name):
|
||||
"""Translate member name to valid PostgreSQL slot name.
|
||||
|
||||
PostgreSQL replication slot names must be valid PostgreSQL names. This function maps the wider space of
|
||||
member names to valid PostgreSQL names. Names are lowercased, dashes and periods common in hostnames
|
||||
are replaced with underscores, other characters are encoded as their unicode codepoint. Name is truncated
|
||||
to 64 characters. Multiple different member names may map to a single slot name."""
|
||||
|
||||
def replace_char(match):
|
||||
c = match.group(0)
|
||||
return '_' if c in '-.' else "u{:04d}".format(ord(c))
|
||||
|
||||
slot_name = re.sub('[^a-z0-9_]', replace_char, member_name.lower())
|
||||
return slot_name[0:63]
|
||||
|
||||
|
||||
def parse_connection_string(value):
|
||||
"""Original Governor stores connection strings for each cluster members if a following format:
|
||||
@@ -42,29 +66,44 @@ def dcs_modules():
|
||||
module_prefix = __package__ + '.'
|
||||
|
||||
if getattr(sys, 'frozen', False):
|
||||
importer = pkgutil.get_importer(dcs_dirname)
|
||||
return [module for module in list(importer.toc) if module.startswith(module_prefix) and module.count('.') == 2]
|
||||
toc = set()
|
||||
for importer in pkgutil.iter_importers(dcs_dirname):
|
||||
if hasattr(importer, 'toc'):
|
||||
toc |= importer.toc
|
||||
return [module for module in toc if module.startswith(module_prefix) and module.count('.') == 2]
|
||||
else:
|
||||
return [module_prefix + name for _, name, is_pkg in pkgutil.iter_modules([dcs_dirname]) if not is_pkg]
|
||||
|
||||
|
||||
def get_dcs(config):
|
||||
available_implementations = set()
|
||||
for module_name in dcs_modules():
|
||||
module = importlib.import_module(module_name)
|
||||
for name in filter(lambda name: not name.startswith('__'), dir(module)): # iterate through module content
|
||||
value = getattr(module, name)
|
||||
name = name.lower()
|
||||
# try to find implementation of AbstractDCS interface, class name must match with module_name
|
||||
if inspect.isclass(value) and issubclass(value, AbstractDCS) and __package__ + '.' + name == module_name:
|
||||
available_implementations.add(name)
|
||||
if name in config: # which has configuration section in the config file
|
||||
# propagate some parameters
|
||||
config[name].update({p: config[p] for p in ('namespace', 'name', 'scope', 'loop_wait',
|
||||
'patronictl', 'ttl', 'retry_timeout') if p in config})
|
||||
return value(config[name])
|
||||
modules = dcs_modules()
|
||||
|
||||
for module_name in modules:
|
||||
name = module_name.split('.')[-1]
|
||||
if name in config: # we will try to import only modules which have configuration section in the config file
|
||||
try:
|
||||
module = importlib.import_module(module_name)
|
||||
for key, item in module.__dict__.items(): # iterate through the module content
|
||||
# try to find implementation of AbstractDCS interface, class name must match with module_name
|
||||
if key.lower() == name and inspect.isclass(item) and issubclass(item, AbstractDCS):
|
||||
# propagate some parameters
|
||||
config[name].update({p: config[p] for p in ('namespace', 'name', 'scope', 'loop_wait',
|
||||
'patronictl', 'ttl', 'retry_timeout') if p in config})
|
||||
return item(config[name])
|
||||
except ImportError:
|
||||
logger.debug('Failed to import %s', module_name)
|
||||
|
||||
available_implementations = []
|
||||
for module_name in modules:
|
||||
name = module_name.split('.')[-1]
|
||||
try:
|
||||
module = importlib.import_module(module_name)
|
||||
available_implementations.extend(name for key, item in module.__dict__.items() if key.lower() == name
|
||||
and inspect.isclass(item) and issubclass(item, AbstractDCS))
|
||||
except ImportError:
|
||||
logger.info('Failed to import %s', module_name)
|
||||
raise PatroniException("""Can not find suitable configuration of distributed configuration store
|
||||
Available implementations: """ + ', '.join(available_implementations))
|
||||
Available implementations: """ + ', '.join(sorted(set(available_implementations))))
|
||||
|
||||
|
||||
class Member(namedtuple('Member', 'index,name,session,data')):
|
||||
@@ -100,14 +139,31 @@ class Member(namedtuple('Member', 'index,name,session,data')):
|
||||
|
||||
@property
|
||||
def conn_url(self):
|
||||
return self.data.get('conn_url')
|
||||
conn_url = self.data.get('conn_url')
|
||||
if conn_url:
|
||||
return conn_url
|
||||
|
||||
conn_kwargs = self.data.get('conn_kwargs')
|
||||
if conn_kwargs:
|
||||
conn_url = uri('postgresql', (conn_kwargs.get('host'), conn_kwargs.get('port', 5432)))
|
||||
self.data['conn_url'] = conn_url
|
||||
return conn_url
|
||||
|
||||
def conn_kwargs(self, auth=None):
|
||||
defaults = {
|
||||
"host": None,
|
||||
"port": None,
|
||||
"database": None
|
||||
}
|
||||
ret = self.data.get('conn_kwargs')
|
||||
if ret:
|
||||
ret = ret.copy()
|
||||
defaults.update(ret)
|
||||
ret = defaults
|
||||
else:
|
||||
r = urlparse(self.conn_url)
|
||||
conn_url = self.conn_url
|
||||
if not conn_url:
|
||||
return {} # due to the invalid conn_url we don't care about authentication parameters
|
||||
r = urlparse(conn_url)
|
||||
ret = {
|
||||
'host': r.hostname,
|
||||
'port': r.port or 5432,
|
||||
@@ -115,11 +171,11 @@ class Member(namedtuple('Member', 'index,name,session,data')):
|
||||
}
|
||||
self.data['conn_kwargs'] = ret.copy()
|
||||
|
||||
# apply any remaining authentication parameters
|
||||
if auth and isinstance(auth, dict):
|
||||
ret.update({k: v for k, v in auth.items() if v is not None})
|
||||
if 'username' in auth:
|
||||
ret['user'] = auth['username']
|
||||
if 'password' in auth:
|
||||
ret['password'] = auth['password']
|
||||
ret['user'] = ret.pop('username')
|
||||
return ret
|
||||
|
||||
@property
|
||||
@@ -151,6 +207,26 @@ class Member(namedtuple('Member', 'index,name,session,data')):
|
||||
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',
|
||||
'no_replication_slot')
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name in RemoteMember.allowed_keys():
|
||||
return self.data.get(name)
|
||||
|
||||
|
||||
class Leader(namedtuple('Leader', 'index,session,member')):
|
||||
|
||||
"""Immutable object (namedtuple) which represents leader key.
|
||||
@@ -170,40 +246,66 @@ class Leader(namedtuple('Leader', 'index,session,member')):
|
||||
def conn_url(self):
|
||||
return self.member.conn_url
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
return self.member.data
|
||||
|
||||
@property
|
||||
def timeline(self):
|
||||
return self.data.get('timeline')
|
||||
|
||||
@property
|
||||
def checkpoint_after_promote(self):
|
||||
"""
|
||||
>>> Leader(1, '', Member.from_node(1, '', '', '{"version":"z"}')).checkpoint_after_promote
|
||||
"""
|
||||
version = self.data.get('version')
|
||||
if version:
|
||||
try:
|
||||
# 1.5.6 is the last version which doesn't expose checkpoint_after_promote: false
|
||||
if tuple(map(int, version.split('.'))) > (1, 5, 6):
|
||||
return self.data['role'] == 'master' and 'checkpoint_after_promote' not in self.data
|
||||
except Exception:
|
||||
logger.debug('Failed to parse Patroni version %s', version)
|
||||
|
||||
|
||||
class Failover(namedtuple('Failover', 'index,leader,candidate,scheduled_at')):
|
||||
|
||||
"""
|
||||
>>> 'Failover' in str(Failover.from_node(1, '{"leader": "cluster_leader"}'))
|
||||
True
|
||||
>>> 'Failover' in str(Failover.from_node(1, {"leader": "cluster_leader"}))
|
||||
True
|
||||
>>> 'Failover' in str(Failover.from_node(1, '{"leader": "cluster_leader", "member": "cluster_candidate"}'))
|
||||
True
|
||||
>>> Failover.from_node(1, 'null') is None
|
||||
True
|
||||
False
|
||||
>>> n = '{"leader": "cluster_leader", "member": "cluster_candidate", "scheduled_at": "2016-01-14T10:09:57.1394Z"}'
|
||||
>>> 'tzinfo=' in str(Failover.from_node(1, n))
|
||||
True
|
||||
>>> Failover.from_node(1, None) is None
|
||||
True
|
||||
False
|
||||
>>> Failover.from_node(1, '{}') is None
|
||||
True
|
||||
False
|
||||
>>> 'abc' in Failover.from_node(1, 'abc:def')
|
||||
True
|
||||
"""
|
||||
@staticmethod
|
||||
def from_node(index, value):
|
||||
if not value:
|
||||
return None
|
||||
|
||||
try:
|
||||
data = json.loads(value)
|
||||
if not data:
|
||||
return None
|
||||
except ValueError:
|
||||
t = [a.strip() for a in value.split(':')]
|
||||
leader = t[0]
|
||||
candidate = t[1] if len(t) > 1 else None
|
||||
return Failover(index, leader, candidate, None) if leader or candidate else None
|
||||
if isinstance(value, dict):
|
||||
data = value
|
||||
elif value:
|
||||
try:
|
||||
data = json.loads(value)
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
except ValueError:
|
||||
t = [a.strip() for a in value.split(':')]
|
||||
leader = t[0]
|
||||
candidate = t[1] if len(t) > 1 else None
|
||||
return Failover(index, leader, candidate, None) if leader or candidate else None
|
||||
else:
|
||||
data = {}
|
||||
|
||||
if data.get('scheduled_at'):
|
||||
data['scheduled_at'] = dateutil.parser.parse(data['scheduled_at'])
|
||||
@@ -220,14 +322,28 @@ class ClusterConfig(namedtuple('ClusterConfig', 'index,data,modify_index')):
|
||||
def from_node(index, data, modify_index=None):
|
||||
"""
|
||||
>>> ClusterConfig.from_node(1, '{') is None
|
||||
True
|
||||
False
|
||||
"""
|
||||
|
||||
try:
|
||||
data = json.loads(data)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return ClusterConfig(index, data, modify_index or index)
|
||||
data = None
|
||||
modify_index = 0
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
return ClusterConfig(index, data, index if modify_index is None else modify_index)
|
||||
|
||||
@property
|
||||
def permanent_slots(self):
|
||||
return isinstance(self.data, dict) and (
|
||||
self.data.get('permanent_replication_slots') or
|
||||
self.data.get('permanent_slots') or self.data.get('slots')
|
||||
) or {}
|
||||
|
||||
@property
|
||||
def max_timelines_history(self):
|
||||
return self.data.get('max_timelines_history', 0)
|
||||
|
||||
|
||||
class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')):
|
||||
@@ -251,8 +367,12 @@ class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')):
|
||||
True
|
||||
>>> SyncState.from_node(1, '{"leader": "leader"}').leader == "leader"
|
||||
True
|
||||
>>> SyncState.from_node(1, {"leader": "leader"}).leader == "leader"
|
||||
True
|
||||
"""
|
||||
if value:
|
||||
if isinstance(value, dict):
|
||||
data = value
|
||||
elif value:
|
||||
try:
|
||||
data = json.loads(value)
|
||||
if not isinstance(data, dict):
|
||||
@@ -282,7 +402,26 @@ class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')):
|
||||
return name is not None and name in (self.leader, self.sync_standby)
|
||||
|
||||
|
||||
class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operation,members,failover,sync')):
|
||||
class TimelineHistory(namedtuple('TimelineHistory', 'index,value,lines')):
|
||||
"""Object representing timeline history file"""
|
||||
|
||||
@staticmethod
|
||||
def from_node(index, value):
|
||||
"""
|
||||
>>> h = TimelineHistory.from_node(1, 2)
|
||||
>>> h.lines
|
||||
[]
|
||||
"""
|
||||
try:
|
||||
lines = json.loads(value)
|
||||
except (TypeError, ValueError):
|
||||
lines = None
|
||||
if not isinstance(lines, list):
|
||||
lines = []
|
||||
return TimelineHistory(index, value, lines)
|
||||
|
||||
|
||||
class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operation,members,failover,sync,history')):
|
||||
|
||||
"""Immutable object (namedtuple) which represents PostgreSQL cluster.
|
||||
Consists of the following fields:
|
||||
@@ -294,6 +433,7 @@ class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operat
|
||||
:param members: list of Member object, all PostgreSQL cluster members including leader
|
||||
:param failover: reference to `Failover` object
|
||||
:param sync: reference to `SyncState` object, last observed synchronous replication state.
|
||||
:param history: reference to `TimelineHistory` object
|
||||
"""
|
||||
|
||||
def is_unlocked(self):
|
||||
@@ -310,8 +450,94 @@ class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operat
|
||||
candidates = [m for m in self.members if m.clonefrom and m.is_running and m.name not in exclude]
|
||||
return candidates[randint(0, len(candidates) - 1)] if candidates else self.leader
|
||||
|
||||
def check_mode(self, mode):
|
||||
return bool(self.config and parse_bool(self.config.data.get(mode)))
|
||||
|
||||
def is_paused(self):
|
||||
return self.config and self.config.data.get('pause', False) or False
|
||||
return self.check_mode('pause')
|
||||
|
||||
def is_synchronous_mode(self):
|
||||
return self.check_mode('synchronous_mode')
|
||||
|
||||
def get_replication_slots(self, my_name, role):
|
||||
# if the replicatefrom tag is set on the member - we should not create the replication slot for it on
|
||||
# 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
|
||||
# master), or if replicatefrom destination member happens to be the current master
|
||||
use_slots = self.config and self.config.data.get('postgresql', {}).get('use_slots', True)
|
||||
if role in ('master', 'standby_leader'):
|
||||
slot_members = [m.name for m in self.members if use_slots and m.name != my_name and
|
||||
(m.replicatefrom is None or m.replicatefrom == my_name or
|
||||
not self.has_member(m.replicatefrom))]
|
||||
permanent_slots = (self.config and self.config.permanent_slots or {}).copy()
|
||||
else:
|
||||
# only manage slots for replicas that replicate from this one, except for the leader among them
|
||||
slot_members = [m.name for m in self.members if use_slots and
|
||||
m.replicatefrom == my_name and m.name != self.leader.name]
|
||||
permanent_slots = {}
|
||||
|
||||
slots = {slot_name_from_member_name(name): {'type': 'physical'} for name in slot_members}
|
||||
|
||||
if len(slots) < len(slot_members):
|
||||
# Find which names are conflicting for a nicer error message
|
||||
slot_conflicts = defaultdict(list)
|
||||
for name in slot_members:
|
||||
slot_conflicts[slot_name_from_member_name(name)].append(name)
|
||||
logger.error("Following cluster members share a replication slot name: %s",
|
||||
"; ".join("{} map to {}".format(", ".join(v), k)
|
||||
for k, v in slot_conflicts.items() if len(v) > 1))
|
||||
|
||||
# "merge" replication slots for members with permanent_replication_slots
|
||||
for name, value in permanent_slots.items():
|
||||
if not slot_name_re.match(name):
|
||||
logger.error("Invalid permanent replication slot name '%s'", name)
|
||||
logger.error("Slot name may only contain lower case letters, numbers, and the underscore chars")
|
||||
continue
|
||||
|
||||
value = deepcopy(value) if value else {'type': 'physical'}
|
||||
if isinstance(value, dict):
|
||||
if 'type' not in value:
|
||||
value['type'] = 'logical' if value.get('database') and value.get('plugin') else 'physical'
|
||||
|
||||
if value['type'] == 'physical':
|
||||
if name != my_name: # Don't try to create permanent physical replication slot for yourself
|
||||
slots[name] = value
|
||||
continue
|
||||
elif value['type'] == 'logical' and value.get('database') and value.get('plugin'):
|
||||
if name in slots:
|
||||
logger.error("Permanent logical replication slot {'%s': %s} is conflicting with" +
|
||||
" physical replication slot for cluster member", name, value)
|
||||
else:
|
||||
slots[name] = value
|
||||
continue
|
||||
|
||||
logger.error("Bad value for slot '%s' in permanent_slots: %s", name, permanent_slots[name])
|
||||
|
||||
return slots
|
||||
|
||||
def has_permanent_logical_slots(self, name):
|
||||
slots = self.get_replication_slots(name, 'master').values()
|
||||
return any(v for v in slots if v.get("type") == "logical")
|
||||
|
||||
@property
|
||||
def timeline(self):
|
||||
"""
|
||||
>>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline
|
||||
0
|
||||
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline
|
||||
1
|
||||
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline
|
||||
0
|
||||
"""
|
||||
if self.history:
|
||||
if self.history.lines:
|
||||
try:
|
||||
return int(self.history.lines[-1][0]) + 1
|
||||
except Exception:
|
||||
logger.error('Failed to parse cluster history from DCS: %s', self.history.lines)
|
||||
elif self.history.value == '[]':
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
@six.add_metaclass(abc.ABCMeta)
|
||||
@@ -321,6 +547,7 @@ class AbstractDCS(object):
|
||||
_CONFIG = 'config'
|
||||
_LEADER = 'leader'
|
||||
_FAILOVER = 'failover'
|
||||
_HISTORY = 'history'
|
||||
_MEMBERS = 'members/'
|
||||
_OPTIME = 'optime'
|
||||
_LEADER_OPTIME = _OPTIME + '/' + _LEADER
|
||||
@@ -332,12 +559,12 @@ class AbstractDCS(object):
|
||||
i.e.: `zookeeper` for zookeeper, `etcd` for etcd, etc...
|
||||
"""
|
||||
self._name = config['name']
|
||||
self._namespace = '/{0}'.format(config.get('namespace', '/service/').strip('/'))
|
||||
self._base_path = '/'.join([self._namespace, config['scope']])
|
||||
self._base_path = re.sub('/+', '/', '/'.join(['', config.get('namespace', 'service'), config['scope']]))
|
||||
self._set_loop_wait(config.get('loop_wait', 10))
|
||||
|
||||
self._ctl = bool(config.get('patronictl', False))
|
||||
self._cluster = None
|
||||
self._cluster_valid_till = 0
|
||||
self._cluster_thread_lock = Lock()
|
||||
self._last_leader_operation = ''
|
||||
self.event = Event()
|
||||
@@ -369,6 +596,10 @@ class AbstractDCS(object):
|
||||
def failover_path(self):
|
||||
return self.client_path(self._FAILOVER)
|
||||
|
||||
@property
|
||||
def history_path(self):
|
||||
return self.client_path(self._HISTORY)
|
||||
|
||||
@property
|
||||
def leader_optime_path(self):
|
||||
return self.client_path(self._LEADER_OPTIME)
|
||||
@@ -381,6 +612,10 @@ class AbstractDCS(object):
|
||||
def set_ttl(self, ttl):
|
||||
"""Set the new ttl value for leader key"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def ttl(self):
|
||||
"""Get new ttl value"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def set_retry_timeout(self, retry_timeout):
|
||||
"""Set the new value for retry_timeout"""
|
||||
@@ -407,23 +642,32 @@ class AbstractDCS(object):
|
||||
If the current node was running as a master and exception raised,
|
||||
instance would be demoted."""
|
||||
|
||||
def get_cluster(self):
|
||||
def _bypass_caches(self):
|
||||
"""Used only in zookeeper"""
|
||||
|
||||
def get_cluster(self, force=False):
|
||||
if force:
|
||||
self._bypass_caches()
|
||||
try:
|
||||
cluster = self._load_cluster()
|
||||
except Exception:
|
||||
self.reset_cluster()
|
||||
raise
|
||||
|
||||
with self._cluster_thread_lock:
|
||||
try:
|
||||
self._load_cluster()
|
||||
except:
|
||||
self._cluster = None
|
||||
raise
|
||||
return self._cluster
|
||||
self._cluster = cluster
|
||||
self._cluster_valid_till = time.time() + self.ttl
|
||||
return cluster
|
||||
|
||||
@property
|
||||
def cluster(self):
|
||||
with self._cluster_thread_lock:
|
||||
return self._cluster
|
||||
return self._cluster if self._cluster_valid_till > time.time() else None
|
||||
|
||||
def reset_cluster(self):
|
||||
with self._cluster_thread_lock:
|
||||
self._cluster = None
|
||||
self._cluster_valid_till = 0
|
||||
|
||||
@abc.abstractmethod
|
||||
def _write_leader_optime(self, last_operation):
|
||||
@@ -436,7 +680,7 @@ class AbstractDCS(object):
|
||||
self._last_leader_operation = last_operation
|
||||
|
||||
@abc.abstractmethod
|
||||
def update_leader(self):
|
||||
def _update_leader(self):
|
||||
"""Update leader key (or session) ttl
|
||||
|
||||
:returns: `!True` if leader key (or session) has been updated successfully.
|
||||
@@ -445,6 +689,18 @@ class AbstractDCS(object):
|
||||
You have to use CAS (Compare And Swap) operation in order to update leader key,
|
||||
for example for etcd `prevValue` parameter must be used."""
|
||||
|
||||
def update_leader(self, last_operation, access_is_restricted=False):
|
||||
"""Update leader key (or session) ttl and optime/leader
|
||||
|
||||
:param last_operation: absolute xlog location in bytes
|
||||
:returns: `!True` if leader key (or session) has been updated successfully.
|
||||
If not, `!False` must be returned and current instance would be demoted."""
|
||||
|
||||
ret = self._update_leader()
|
||||
if ret and last_operation:
|
||||
self.write_leader_optime(last_operation)
|
||||
return ret
|
||||
|
||||
@abc.abstractmethod
|
||||
def attempt_to_acquire_leader(self, permanent=False):
|
||||
"""Attempt to acquire leader lock
|
||||
@@ -470,7 +726,6 @@ class AbstractDCS(object):
|
||||
|
||||
if scheduled_at:
|
||||
failover_value['scheduled_at'] = scheduled_at.isoformat()
|
||||
|
||||
return self.set_failover_value(json.dumps(failover_value, separators=(',', ':')), index)
|
||||
|
||||
@abc.abstractmethod
|
||||
@@ -478,12 +733,12 @@ class AbstractDCS(object):
|
||||
"""Create or update `/config` key"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def touch_member(self, data, ttl=None, permanent=False):
|
||||
def touch_member(self, data, permanent=False):
|
||||
"""Update member key in DCS.
|
||||
This method should create or update key with the name = '/members/' + `~self._name`
|
||||
and value = data in a given DCS.
|
||||
|
||||
:param data: json serialized information about instance (including connection strings)
|
||||
:param data: information about instance (including connection strings)
|
||||
:param ttl: ttl for member key, optional parameter. If it is None `~self.member_ttl will be used`
|
||||
:param permanent: if set to `!True`, the member key will never expire.
|
||||
Used in patronictl for the external master.
|
||||
@@ -508,10 +763,19 @@ class AbstractDCS(object):
|
||||
otherwise it should return `!False`"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def delete_leader(self):
|
||||
"""Voluntarily remove leader key from DCS
|
||||
def _delete_leader(self):
|
||||
"""Remove leader key from DCS.
|
||||
This method should remove leader key if current instance is the leader"""
|
||||
|
||||
def delete_leader(self, last_operation=None):
|
||||
"""Update optime/leader and voluntarily remove leader key from DCS.
|
||||
This method should remove leader key if current instance is the leader.
|
||||
:param last_operation: latest checkpoint location in bytes"""
|
||||
|
||||
if last_operation:
|
||||
self.write_leader_optime(last_operation)
|
||||
return self._delete_leader()
|
||||
|
||||
@abc.abstractmethod
|
||||
def cancel_initialization(self):
|
||||
""" Removes the initialize key for a cluster """
|
||||
@@ -520,8 +784,18 @@ class AbstractDCS(object):
|
||||
def delete_cluster(self):
|
||||
"""Delete cluster from DCS"""
|
||||
|
||||
@staticmethod
|
||||
def sync_state(leader, sync_standby):
|
||||
"""Build sync_state dict"""
|
||||
return {'leader': leader, 'sync_standby': sync_standby}
|
||||
|
||||
def write_sync_state(self, leader, sync_standby, index=None):
|
||||
return self.set_sync_state_value(json.dumps({'leader': leader, 'sync_standby': sync_standby}), index=index)
|
||||
sync_value = self.sync_state(leader, sync_standby)
|
||||
return self.set_sync_state_value(json.dumps(sync_value, separators=(',', ':')), index)
|
||||
|
||||
@abc.abstractmethod
|
||||
def set_history_value(self, value):
|
||||
""""""
|
||||
|
||||
@abc.abstractmethod
|
||||
def set_sync_state_value(self, value, index=None):
|
||||
|
||||
+261
-44
@@ -1,18 +1,22 @@
|
||||
from __future__ import absolute_import
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import urllib3
|
||||
|
||||
from consul import ConsulException, NotFound, base
|
||||
from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState
|
||||
from patroni.exceptions import DCSError
|
||||
from patroni.utils import Retry, RetryFailedError
|
||||
from urllib3.exceptions import HTTPError
|
||||
from six.moves.urllib.parse import urlencode
|
||||
from six.moves.urllib.parse import urlencode, urlparse, quote
|
||||
from six.moves.http_client import HTTPException
|
||||
|
||||
from . import AbstractDCS, Cluster, ClusterConfig, Failover, Leader, Member, SyncState, TimelineHistory
|
||||
from ..exceptions import DCSError
|
||||
from ..utils import deep_compare, parse_bool, Retry, RetryFailedError, split_host_port, uri, USER_AGENT
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -24,21 +28,42 @@ class ConsulInternalError(ConsulException):
|
||||
"""An internal Consul server error occurred"""
|
||||
|
||||
|
||||
class InvalidSessionTTL(ConsulException):
|
||||
"""Session TTL is too small or too big"""
|
||||
|
||||
|
||||
class InvalidSession(ConsulException):
|
||||
"""invalid session"""
|
||||
|
||||
|
||||
class HTTPClient(object):
|
||||
|
||||
def __init__(self, host='127.0.0.1', port=8500, scheme='http', verify=True, timeout=10):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.scheme = scheme
|
||||
self.verify = verify
|
||||
self.set_read_timeout(timeout)
|
||||
self.base_uri = '{0}://{1}:{2}'.format(self.scheme, self.host, self.port)
|
||||
self.http = urllib3.PoolManager(num_pools=10)
|
||||
def __init__(self, host='127.0.0.1', port=8500, token=None, scheme='http', verify=True, cert=None, ca_cert=None):
|
||||
self.token = token
|
||||
self._read_timeout = 10
|
||||
self.base_uri = uri(scheme, (host, port))
|
||||
kwargs = {}
|
||||
if cert:
|
||||
if isinstance(cert, tuple):
|
||||
# Key and cert are separate
|
||||
kwargs['cert_file'] = cert[0]
|
||||
kwargs['key_file'] = cert[1]
|
||||
else:
|
||||
# combined certificate
|
||||
kwargs['cert_file'] = cert
|
||||
if ca_cert:
|
||||
kwargs['ca_certs'] = ca_cert
|
||||
kwargs['cert_reqs'] = ssl.CERT_REQUIRED if verify or ca_cert else ssl.CERT_NONE
|
||||
self.http = urllib3.PoolManager(num_pools=10, maxsize=10, **kwargs)
|
||||
self._ttl = None
|
||||
|
||||
def set_read_timeout(self, timeout):
|
||||
self._read_timeout = timeout/3.0
|
||||
|
||||
@property
|
||||
def ttl(self):
|
||||
return self._ttl
|
||||
|
||||
def set_ttl(self, ttl):
|
||||
ret = self._ttl != ttl
|
||||
self._ttl = ttl
|
||||
@@ -48,7 +73,13 @@ class HTTPClient(object):
|
||||
def response(response):
|
||||
data = response.data.decode('utf-8')
|
||||
if response.status == 500:
|
||||
raise ConsulInternalError('{0} {1}'.format(response.status, data))
|
||||
msg = '{0} {1}'.format(response.status, data)
|
||||
if data.startswith('Invalid Session TTL'):
|
||||
raise InvalidSessionTTL(msg)
|
||||
elif data.startswith('invalid session'):
|
||||
raise InvalidSession(msg)
|
||||
else:
|
||||
raise ConsulInternalError(msg)
|
||||
return base.Response(response.status, response.headers, data)
|
||||
|
||||
def uri(self, path, params=None):
|
||||
@@ -67,20 +98,48 @@ class HTTPClient(object):
|
||||
data = '{' + ttl + '}'
|
||||
else:
|
||||
data = data[:-1] + ', ' + ttl + '}'
|
||||
if isinstance(params, list): # starting from v1.1.0 python-consul switched from `dict` to `list` for params
|
||||
params = {k: v for k, v in params}
|
||||
kwargs = {'retries': 0, 'preload_content': False, 'body': data}
|
||||
if method == 'get' and isinstance(params, dict) and 'index' in params:
|
||||
kwargs['timeout'] = (float(params['wait'][:-1]) if 'wait' in params else 300) + 1
|
||||
timeout = float(params['wait'][:-1]) if 'wait' in params else 300
|
||||
# According to the documentation a small random amount of additional wait time is added to the
|
||||
# supplied maximum wait time to spread out the wake up time of any concurrent requests. This adds
|
||||
# up to wait / 16 additional time to the maximum duration. Since our goal is actually getting a
|
||||
# response rather read timeout we will add to the timeout a sligtly bigger value.
|
||||
kwargs['timeout'] = timeout + max(timeout/15.0, 1)
|
||||
else:
|
||||
kwargs['timeout'] = self._read_timeout
|
||||
token = params.pop('token', self.token) if isinstance(params, dict) else self.token
|
||||
kwargs['headers'] = urllib3.make_headers(user_agent=USER_AGENT)
|
||||
if token:
|
||||
kwargs['headers']['X-Consul-Token'] = token
|
||||
return callback(self.response(self.http.request(method.upper(), self.uri(path, params), **kwargs)))
|
||||
return wrapper
|
||||
|
||||
|
||||
class ConsulClient(base.Consul):
|
||||
|
||||
@staticmethod
|
||||
def connect(host, port, scheme, verify=True):
|
||||
return HTTPClient(host, port, scheme, verify)
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._cert = kwargs.pop('cert', None)
|
||||
self._ca_cert = kwargs.pop('ca_cert', None)
|
||||
self.token = kwargs.get('token')
|
||||
super(ConsulClient, self).__init__(*args, **kwargs)
|
||||
|
||||
def connect(self, *args, **kwargs):
|
||||
kwargs.update(dict(zip(['host', 'port', 'scheme', 'verify'], args)))
|
||||
if self._cert:
|
||||
kwargs['cert'] = self._cert
|
||||
if self._ca_cert:
|
||||
kwargs['ca_cert'] = self._ca_cert
|
||||
if self.token:
|
||||
kwargs['token'] = self.token
|
||||
return HTTPClient(**kwargs)
|
||||
|
||||
def reload_config(self, config):
|
||||
self.http.token = self.token = config.get('token')
|
||||
self.consistency = config.get('consistency', 'default')
|
||||
self.dc = config.get('dc')
|
||||
|
||||
|
||||
def catch_consul_errors(func):
|
||||
@@ -92,6 +151,31 @@ def catch_consul_errors(func):
|
||||
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):
|
||||
|
||||
def __init__(self, config):
|
||||
@@ -103,12 +187,43 @@ class Consul(AbstractDCS):
|
||||
retry_exceptions=(ConsulInternalError, HTTPException,
|
||||
HTTPError, socket.error, socket.timeout))
|
||||
|
||||
self._my_member_data = None
|
||||
host, port = config.get('host', '127.0.0.1:8500').split(':')
|
||||
self._client = ConsulClient(host=host, port=port)
|
||||
kwargs = {}
|
||||
if 'url' in config:
|
||||
r = urlparse(config['url'])
|
||||
config.update({'scheme': r.scheme, 'host': r.hostname, 'port': r.port or 8500})
|
||||
elif 'host' in config:
|
||||
host, port = split_host_port(config.get('host', '127.0.0.1:8500'), 8500)
|
||||
config['host'] = host
|
||||
if 'port' not in config:
|
||||
config['port'] = int(port)
|
||||
|
||||
if config.get('cacert'):
|
||||
config['ca_cert'] = config.pop('cacert')
|
||||
|
||||
if config.get('key') and config.get('cert'):
|
||||
config['cert'] = (config['cert'], config['key'])
|
||||
|
||||
config_keys = ('host', 'port', 'token', 'scheme', 'cert', 'ca_cert', 'dc', 'consistency')
|
||||
kwargs = {p: config.get(p) for p in config_keys if config.get(p)}
|
||||
|
||||
verify = config.get('verify')
|
||||
if not isinstance(verify, bool):
|
||||
verify = parse_bool(verify)
|
||||
if isinstance(verify, bool):
|
||||
kwargs['verify'] = verify
|
||||
|
||||
self._client = ConsulClient(**kwargs)
|
||||
self.set_retry_timeout(config['retry_timeout'])
|
||||
self.set_ttl(config.get('ttl') or 30)
|
||||
self._last_session_refresh = 0
|
||||
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:
|
||||
self.create_session()
|
||||
|
||||
@@ -123,15 +238,32 @@ class Consul(AbstractDCS):
|
||||
logger.info('waiting on consul')
|
||||
time.sleep(5)
|
||||
|
||||
def reload_config(self, config):
|
||||
super(Consul, self).reload_config(config)
|
||||
self._client.reload_config(config.get('consul', {}))
|
||||
|
||||
def set_ttl(self, ttl):
|
||||
if self._client.http.set_ttl(ttl/2.0): # Consul multiplies the TTL by 2x
|
||||
self._session = None
|
||||
self.__do_not_watch = True
|
||||
|
||||
@property
|
||||
def ttl(self):
|
||||
return self._client.http.ttl
|
||||
|
||||
def set_retry_timeout(self, retry_timeout):
|
||||
self._retry.deadline = retry_timeout
|
||||
self._client.http.set_read_timeout(retry_timeout)
|
||||
|
||||
def adjust_ttl(self):
|
||||
try:
|
||||
settings = self._client.agent.self()
|
||||
min_ttl = (settings['Config']['SessionTTLMin'] or 10000000000)/1000000000.0
|
||||
logger.warning('Changing Session TTL from %s to %s', self._client.http.ttl, min_ttl)
|
||||
self._client.http.set_ttl(min_ttl)
|
||||
except Exception:
|
||||
logger.exception('adjust_ttl')
|
||||
|
||||
def _do_refresh_session(self):
|
||||
""":returns: `!True` if it had to create new session"""
|
||||
if self._session and self._last_session_refresh + self._loop_wait > time.time():
|
||||
@@ -144,8 +276,15 @@ class Consul(AbstractDCS):
|
||||
self._session = None
|
||||
ret = not self._session
|
||||
if ret:
|
||||
self._session = self._client.session.create(name=self._scope + '-' + self._name,
|
||||
lock_delay=0.001, behavior='delete')
|
||||
try:
|
||||
self._session = self._client.session.create(name=self._scope + '-' + self._name,
|
||||
checks=self.__session_checks,
|
||||
lock_delay=0.001, behavior='delete')
|
||||
except InvalidSessionTTL:
|
||||
logger.exception('session.create')
|
||||
self.adjust_ttl()
|
||||
raise
|
||||
|
||||
self._last_session_refresh = time.time()
|
||||
return ret
|
||||
|
||||
@@ -174,7 +313,7 @@ class Consul(AbstractDCS):
|
||||
nodes = {}
|
||||
for node in results:
|
||||
node['Value'] = (node['Value'] or b'').decode('utf-8')
|
||||
nodes[os.path.relpath(node['Key'], path)] = node
|
||||
nodes[node['Key'][len(path):].lstrip('/')] = node
|
||||
|
||||
# get initialize flag
|
||||
initialize = nodes.get(self._INITIALIZE)
|
||||
@@ -184,6 +323,10 @@ class Consul(AbstractDCS):
|
||||
config = nodes.get(self._CONFIG)
|
||||
config = config and ClusterConfig.from_node(config['ModifyIndex'], config['Value'])
|
||||
|
||||
# get timeline history
|
||||
history = nodes.get(self._HISTORY)
|
||||
history = history and TimelineHistory.from_node(history['ModifyIndex'], history['Value'])
|
||||
|
||||
# get last leader operation
|
||||
last_leader_operation = nodes.get(self._LEADER_OPTIME)
|
||||
last_leader_operation = 0 if last_leader_operation is None else int(last_leader_operation['Value'])
|
||||
@@ -213,46 +356,115 @@ class Consul(AbstractDCS):
|
||||
sync = nodes.get(self._SYNC)
|
||||
sync = SyncState.from_node(sync and sync['ModifyIndex'], sync and sync['Value'])
|
||||
|
||||
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync)
|
||||
return Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
|
||||
except NotFound:
|
||||
self._cluster = Cluster(None, None, None, None, [], None, None)
|
||||
except:
|
||||
return Cluster(None, None, None, None, [], None, None, None)
|
||||
except Exception:
|
||||
logger.exception('get_cluster')
|
||||
raise ConsulError('Consul is not responding properly')
|
||||
|
||||
def touch_member(self, data, **kwargs):
|
||||
@catch_consul_errors
|
||||
def touch_member(self, data, permanent=False):
|
||||
cluster = self.cluster
|
||||
member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
|
||||
create_member = self.refresh_session()
|
||||
|
||||
try:
|
||||
create_member = not permanent and self.refresh_session()
|
||||
except DCSError:
|
||||
return False
|
||||
|
||||
if member and (create_member or member.session != self._session):
|
||||
try:
|
||||
self._client.kv.delete(self.member_path)
|
||||
create_member = True
|
||||
except Exception:
|
||||
return False
|
||||
self._client.kv.delete(self.member_path)
|
||||
create_member = True
|
||||
|
||||
if not create_member and member and data == self._my_member_data:
|
||||
if not create_member and member and deep_compare(data, member.data):
|
||||
return True
|
||||
|
||||
try:
|
||||
args = {} if kwargs.get('permanent', False) else {'acquire': self._session}
|
||||
self._client.kv.put(self.member_path, data, **args)
|
||||
self._my_member_data = data
|
||||
args = {} if permanent else {'acquire': self._session}
|
||||
self._client.kv.put(self.member_path, json.dumps(data, separators=(',', ':')), **args)
|
||||
if self._register_service:
|
||||
self.update_service(not create_member and member and member.data or {}, data)
|
||||
return True
|
||||
except InvalidSession:
|
||||
self._session = None
|
||||
logger.error('Our session disappeared from Consul, can not "touch_member"')
|
||||
except Exception:
|
||||
logger.exception('touch_member')
|
||||
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'].replace('_', '-')
|
||||
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='{0}s'.format(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', 'standby-leader']:
|
||||
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
|
||||
def _do_attempt_to_acquire_leader(self, permanent):
|
||||
try:
|
||||
kwargs = {} if permanent else {'acquire': self._session}
|
||||
return self.retry(self._client.kv.put, self.leader_path, self._name, **kwargs)
|
||||
except InvalidSession:
|
||||
self._session = None
|
||||
logger.error('Our session disappeared from Consul. Will try to get a new one and retry attempt')
|
||||
self.refresh_session()
|
||||
return self.retry(self._client.kv.put, self.leader_path, self._name, acquire=self._session)
|
||||
|
||||
def attempt_to_acquire_leader(self, permanent=False):
|
||||
if not self._session and not permanent:
|
||||
self.refresh_session()
|
||||
|
||||
args = {} if permanent else {'acquire': self._session}
|
||||
ret = self.retry(self._client.kv.put, self.leader_path, self._name, **args)
|
||||
ret = self._do_attempt_to_acquire_leader(permanent)
|
||||
if not ret:
|
||||
logger.info('Could not take out TTL lock')
|
||||
|
||||
return ret
|
||||
|
||||
def take_leader(self):
|
||||
@@ -271,7 +483,7 @@ class Consul(AbstractDCS):
|
||||
return self._client.kv.put(self.leader_optime_path, last_operation)
|
||||
|
||||
@catch_consul_errors
|
||||
def update_leader(self):
|
||||
def _update_leader(self):
|
||||
if self._session:
|
||||
self.retry(self._client.session.renew, self._session)
|
||||
self._last_session_refresh = time.time()
|
||||
@@ -291,20 +503,25 @@ class Consul(AbstractDCS):
|
||||
return self.retry(self._client.kv.delete, self.client_path(''), recurse=True)
|
||||
|
||||
@catch_consul_errors
|
||||
def delete_leader(self):
|
||||
def set_history_value(self, value):
|
||||
return self._client.kv.put(self.history_path, value)
|
||||
|
||||
@catch_consul_errors
|
||||
def _delete_leader(self):
|
||||
cluster = self.cluster
|
||||
if cluster and isinstance(cluster.leader, Leader) and cluster.leader.name == self._name:
|
||||
return self._client.kv.delete(self.leader_path, cas=cluster.leader.index)
|
||||
|
||||
@catch_consul_errors
|
||||
def set_sync_state_value(self, value, index=None):
|
||||
return self._client.kv.put(self.sync_path, value, cas=index)
|
||||
return self.retry(self._client.kv.put, self.sync_path, value, cas=index)
|
||||
|
||||
@catch_consul_errors
|
||||
def delete_sync_state(self, index=None):
|
||||
return self._client.kv.delete(self.sync_path, cas=index)
|
||||
return self.retry(self._client.kv.delete, self.sync_path, cas=index)
|
||||
|
||||
def watch(self, leader_index, timeout):
|
||||
self._last_session_refresh = 0
|
||||
if self.__do_not_watch:
|
||||
self.__do_not_watch = False
|
||||
return True
|
||||
@@ -316,7 +533,7 @@ class Consul(AbstractDCS):
|
||||
idx, _ = self._client.kv.get(self.leader_path, index=leader_index, wait=str(timeout) + 's')
|
||||
return str(idx) != str(leader_index)
|
||||
except (ConsulException, HTTPException, HTTPError, socket.error, socket.timeout):
|
||||
logging.exception('watch')
|
||||
logger.exception('watch')
|
||||
|
||||
timeout = end_time - time.time()
|
||||
|
||||
|
||||
+256
-132
@@ -1,28 +1,35 @@
|
||||
from __future__ import absolute_import
|
||||
import etcd
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import urllib3.util.connection
|
||||
import random
|
||||
import requests
|
||||
import six
|
||||
import socket
|
||||
import time
|
||||
|
||||
from dns.exception import DNSException
|
||||
from dns import resolver
|
||||
from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState
|
||||
from patroni.exceptions import DCSError
|
||||
from patroni.utils import Retry, RetryFailedError
|
||||
from urllib3.exceptions import HTTPError, ReadTimeoutError
|
||||
from requests.exceptions import RequestException
|
||||
from urllib3 import Timeout
|
||||
from urllib3.exceptions import HTTPError, ReadTimeoutError, ProtocolError
|
||||
from six.moves.queue import Queue
|
||||
from six.moves.http_client import HTTPException
|
||||
from six.moves.urllib_parse import urlparse
|
||||
from threading import Thread
|
||||
|
||||
from . import AbstractDCS, Cluster, ClusterConfig, Failover, Leader, Member, SyncState, TimelineHistory
|
||||
from ..exceptions import DCSError
|
||||
from ..request import get as requests_get
|
||||
from ..utils import Retry, RetryFailedError, split_host_port, uri, USER_AGENT
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EtcdRaftInternal(etcd.EtcdException):
|
||||
"""Raft Internal Error"""
|
||||
|
||||
|
||||
class EtcdError(DCSError):
|
||||
pass
|
||||
|
||||
@@ -63,12 +70,15 @@ class DnsCachingResolver(Thread):
|
||||
def resolve_async(self, host, port, attempt=0):
|
||||
self._resolve_queue.put(((host, port), attempt))
|
||||
|
||||
def remove(self, host, port):
|
||||
self._cache.pop((host, port), None)
|
||||
|
||||
@staticmethod
|
||||
def _do_resolve(host, port):
|
||||
try:
|
||||
return socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
|
||||
except socket.gaierror:
|
||||
logger.warning('failed to resolve host %s', host)
|
||||
except Exception as e:
|
||||
logger.warning('failed to resolve host %s: %s', host, e)
|
||||
return []
|
||||
|
||||
|
||||
@@ -81,30 +91,68 @@ class Client(etcd.Client):
|
||||
args = {p: config.get(p) for p in ('host', 'port', 'protocol', 'use_proxies', 'username', 'password',
|
||||
'cert', 'ca_cert') if config.get(p)}
|
||||
super(Client, self).__init__(read_timeout=config['retry_timeout'], **args)
|
||||
# For some reason python3-etcd on debian and ubuntu are not based on the latest version
|
||||
# Workaround for the case when https://github.com/jplana/python-etcd/pull/196 is not applied
|
||||
self.http.connection_pool_kw.pop('ssl_version', None)
|
||||
self._config = config
|
||||
self._initial_machines_cache = []
|
||||
self._load_machines_cache()
|
||||
self._allow_reconnect = not self._use_proxies
|
||||
self._allow_reconnect = True
|
||||
# allow passing retry argument to api_execute in params
|
||||
self._comparison_conditions.add('retry')
|
||||
self._read_options.add('retry')
|
||||
self._del_conditions.add('retry')
|
||||
|
||||
def _build_request_parameters(self):
|
||||
def _calculate_timeouts(self, etcd_nodes, timeout=None):
|
||||
"""Calculate a request timeout and number of retries per single etcd node.
|
||||
In case if the timeout per node is too small (less than one second) we will reduce the number of nodes.
|
||||
For the cluster with only one node we will try to do 2 retries.
|
||||
For clusters with 2 nodes we will try to do 1 retry for every node.
|
||||
No retries for clusters with 3 or more nodes. We better rely on switching to a different node."""
|
||||
|
||||
per_node_timeout = timeout = float(timeout or self.read_timeout)
|
||||
|
||||
max_retries = 4 - min(etcd_nodes, 3)
|
||||
per_node_retries = 1
|
||||
min_timeout = 1.0
|
||||
|
||||
while etcd_nodes > 0:
|
||||
per_node_timeout = float(timeout) / etcd_nodes
|
||||
if per_node_timeout >= min_timeout:
|
||||
# for small clusters we will try to do more than on try on every node
|
||||
while per_node_retries < max_retries and per_node_timeout / (per_node_retries + 1) >= min_timeout:
|
||||
per_node_retries += 1
|
||||
per_node_timeout /= per_node_retries
|
||||
break
|
||||
# if the timeout per one node is to small try to reduce number of nodes
|
||||
etcd_nodes -= 1
|
||||
max_retries = 1
|
||||
|
||||
return etcd_nodes, per_node_timeout, per_node_retries - 1
|
||||
|
||||
def _get_headers(self):
|
||||
basic_auth = ':'.join((self.username, self.password)) if self.username and self.password else None
|
||||
return urllib3.make_headers(basic_auth=basic_auth, user_agent=USER_AGENT)
|
||||
|
||||
def _build_request_parameters(self, etcd_nodes, timeout=None):
|
||||
kwargs = {'headers': self._get_headers(), 'redirect': self.allow_redirect}
|
||||
|
||||
# calculate the number of retries and timeout *per node*
|
||||
# actual number of retries depends on the number of nodes
|
||||
etcd_nodes = len(self._machines_cache) + 1
|
||||
kwargs['retries'] = 0 if etcd_nodes > 3 else (1 if etcd_nodes > 1 else 2)
|
||||
|
||||
# if etcd_nodes > 3:
|
||||
# kwargs.update({'retries': 0, 'timeout': float(self.read_timeout)/etcd_nodes})
|
||||
# elif etcd_nodes > 1:
|
||||
# kwargs.update({'retries': 1, 'timeout': self.read_timeout/2.0/etcd_nodes})
|
||||
# else:
|
||||
# kwargs.update({'retries': 2, 'timeout': self.read_timeout/3.0})
|
||||
kwargs['timeout'] = self.read_timeout/float(kwargs['retries'] + 1)/etcd_nodes
|
||||
if timeout is not None:
|
||||
kwargs.update(retries=0, timeout=timeout)
|
||||
else:
|
||||
_, per_node_timeout, per_node_retries = self._calculate_timeouts(etcd_nodes)
|
||||
connect_timeout = max(1, per_node_timeout/2)
|
||||
kwargs.update(timeout=Timeout(connect=connect_timeout, total=per_node_timeout), retries=per_node_retries)
|
||||
return kwargs
|
||||
|
||||
def set_machines_cache_ttl(self, cache_ttl):
|
||||
self._machines_cache_ttl = cache_ttl
|
||||
|
||||
@property
|
||||
def machines_cache(self):
|
||||
base_uri, cache = self._base_uri, self._machines_cache
|
||||
return ([base_uri] if base_uri in cache else []) + [machine for machine in cache if machine != base_uri]
|
||||
|
||||
@property
|
||||
def machines(self):
|
||||
"""Original `machines` method(property) of `etcd.Client` class raise exception
|
||||
@@ -117,56 +165,64 @@ class Client(etcd.Client):
|
||||
Also this method implements the same timeout-retry logic as `api_execute`, because
|
||||
the original method was retrying 2 times with the `read_timeout` on each node."""
|
||||
|
||||
kwargs = self._build_request_parameters()
|
||||
machines_cache = self.machines_cache
|
||||
kwargs = self._build_request_parameters(len(machines_cache))
|
||||
|
||||
while True:
|
||||
for base_uri in machines_cache:
|
||||
try:
|
||||
response = self.http.request(self._MGET, self._base_uri + self.version_prefix + '/machines', **kwargs)
|
||||
machines = [n.strip() for n in self._handle_server_response(response).data.decode('utf-8').split(',')]
|
||||
response = self.http.request(self._MGET, base_uri + self.version_prefix + '/machines', **kwargs)
|
||||
data = self._handle_server_response(response).data.decode('utf-8')
|
||||
machines = [m.strip() for m in data.split(',') if m.strip()]
|
||||
logger.debug("Retrieved list of machines: %s", machines)
|
||||
random.shuffle(machines)
|
||||
for url in machines:
|
||||
r = urlparse(url)
|
||||
port = r.port or (443 if r.scheme == 'https' else 80)
|
||||
self._dns_resolver.resolve_async(r.hostname, port)
|
||||
return machines
|
||||
if machines:
|
||||
random.shuffle(machines)
|
||||
self._update_dns_cache(self._dns_resolver.resolve_async, machines)
|
||||
return machines
|
||||
except Exception as e:
|
||||
# We can't get the list of machines, if one server is in the
|
||||
# machines cache, try on it
|
||||
logger.error("Failed to get list of machines from %s%s: %r", self._base_uri, self.version_prefix, e)
|
||||
if self._machines_cache:
|
||||
self._base_uri = self._machines_cache.pop(0)
|
||||
logger.info("Retrying on %s", self._base_uri)
|
||||
elif self._update_machines_cache:
|
||||
raise etcd.EtcdException("Could not get the list of servers, "
|
||||
"maybe you provided the wrong "
|
||||
"host(s) to connect to?")
|
||||
else:
|
||||
return []
|
||||
self.http.clear()
|
||||
logger.error("Failed to get list of machines from %s%s: %r", base_uri, self.version_prefix, e)
|
||||
|
||||
raise etcd.EtcdConnectionFailed('No more machines in the cluster')
|
||||
|
||||
def set_read_timeout(self, timeout):
|
||||
self._read_timeout = timeout
|
||||
|
||||
def _do_http_request(self, request_executor, method, url, fields=None, **kwargs):
|
||||
try:
|
||||
response = request_executor(method, url, fields=fields, **kwargs)
|
||||
response.data.decode('utf-8')
|
||||
self._check_cluster_id(response)
|
||||
except (HTTPError, HTTPException, socket.error, socket.timeout) as e:
|
||||
if (isinstance(fields, dict) and fields.get("wait") == "true" and
|
||||
isinstance(e, ReadTimeoutError)):
|
||||
logger.debug("Watch timed out.")
|
||||
raise etcd.EtcdWatchTimedOut("Watch timed out: {0}".format(e), cause=e)
|
||||
logger.error("Request to server %s failed: %r", self._base_uri, e)
|
||||
logger.info("Reconnection allowed, looking for another server.")
|
||||
self._base_uri = self._next_server(cause=e)
|
||||
response = False
|
||||
return response
|
||||
def _do_http_request(self, retry, machines_cache, request_executor, method, path, fields=None, **kwargs):
|
||||
some_request_failed = False
|
||||
for i, base_uri in enumerate(machines_cache):
|
||||
if i > 0:
|
||||
logger.info("Retrying on %s", base_uri)
|
||||
try:
|
||||
response = request_executor(method, base_uri + path, fields=fields, **kwargs)
|
||||
response.data.decode('utf-8')
|
||||
self._check_cluster_id(response)
|
||||
if some_request_failed:
|
||||
self.set_base_uri(base_uri)
|
||||
self._refresh_machines_cache()
|
||||
return response
|
||||
except (HTTPError, HTTPException, socket.error, socket.timeout) as e:
|
||||
self.http.clear()
|
||||
# switch to the next etcd node because we don't know exactly what happened,
|
||||
# whether the key didn't received an update or there is a network problem.
|
||||
if not retry and i + 1 < len(machines_cache):
|
||||
self.set_base_uri(machines_cache[i + 1])
|
||||
if (isinstance(fields, dict) and fields.get("wait") == "true" and
|
||||
isinstance(e, (ReadTimeoutError, ProtocolError))):
|
||||
logger.debug("Watch timed out.")
|
||||
raise etcd.EtcdWatchTimedOut("Watch timed out: {0}".format(e), cause=e)
|
||||
logger.error("Request to server %s failed: %r", base_uri, e)
|
||||
logger.info("Reconnection allowed, looking for another server.")
|
||||
if not retry:
|
||||
raise etcd.EtcdException('{0} {1} request failed'.format(method, path))
|
||||
some_request_failed = True
|
||||
|
||||
raise etcd.EtcdConnectionFailed('No more machines in the cluster')
|
||||
|
||||
def api_execute(self, path, method, params=None, timeout=None):
|
||||
if not path.startswith('/'):
|
||||
raise ValueError('Path does not start with /')
|
||||
|
||||
retry = params.pop('retry', None) if isinstance(params, dict) else None
|
||||
kwargs = {'fields': params, 'preload_content': False}
|
||||
|
||||
if method in [self._MGET, self._MDELETE]:
|
||||
@@ -180,35 +236,37 @@ class Client(etcd.Client):
|
||||
# Update machines_cache if previous attempt of update has failed
|
||||
if self._update_machines_cache:
|
||||
self._load_machines_cache()
|
||||
elif time.time() - self._machines_cache_updated > self._machines_cache_ttl:
|
||||
self._machines_cache = self.machines
|
||||
if self._base_uri in self._machines_cache:
|
||||
self._machines_cache.remove(self._base_uri)
|
||||
self._machines_cache_updated = time.time()
|
||||
elif not self._use_proxies and time.time() - self._machines_cache_updated > self._machines_cache_ttl:
|
||||
self._refresh_machines_cache()
|
||||
|
||||
kwargs.update(self._build_request_parameters())
|
||||
machines_cache = self.machines_cache
|
||||
etcd_nodes = len(machines_cache)
|
||||
kwargs.update(self._build_request_parameters(etcd_nodes, timeout))
|
||||
|
||||
if timeout is not None:
|
||||
kwargs.update({'retries': 0, 'timeout': timeout})
|
||||
|
||||
response = False
|
||||
|
||||
try:
|
||||
some_request_failed = False
|
||||
while not response:
|
||||
response = self._do_http_request(request_executor, method, self._base_uri + path, **kwargs)
|
||||
|
||||
if response is False:
|
||||
some_request_failed = True
|
||||
if some_request_failed and not self._use_proxies:
|
||||
self._machines_cache = self.machines
|
||||
if self._base_uri in self._machines_cache:
|
||||
self._machines_cache.remove(self._base_uri)
|
||||
except etcd.EtcdConnectionFailed:
|
||||
self._update_machines_cache = True
|
||||
if not response:
|
||||
while True:
|
||||
try:
|
||||
response = self._do_http_request(retry, machines_cache, request_executor, method, path, **kwargs)
|
||||
return self._handle_server_response(response)
|
||||
except etcd.EtcdWatchTimedOut:
|
||||
raise
|
||||
return self._handle_server_response(response)
|
||||
except etcd.EtcdConnectionFailed as ex:
|
||||
try:
|
||||
if self._load_machines_cache():
|
||||
machines_cache = self.machines_cache
|
||||
etcd_nodes = len(machines_cache)
|
||||
except Exception as e:
|
||||
logger.debug('Failed to update list of etcd nodes: %r', e)
|
||||
sleeptime = retry.sleeptime
|
||||
remaining_time = retry.stoptime - sleeptime - time.time()
|
||||
nodes, timeout, retries = self._calculate_timeouts(etcd_nodes, remaining_time)
|
||||
if nodes == 0:
|
||||
self._update_machines_cache = True
|
||||
raise ex
|
||||
retry.sleep_func(sleeptime)
|
||||
retry.update_delay()
|
||||
# We still have some time left. Partially reduce `machines_cache` and retry request
|
||||
kwargs.update(timeout=Timeout(connect=max(1, timeout/2), total=timeout), retries=retries)
|
||||
machines_cache = machines_cache[:nodes]
|
||||
|
||||
@staticmethod
|
||||
def get_srv_record(host):
|
||||
@@ -227,15 +285,15 @@ class Client(etcd.Client):
|
||||
protocol = 'https' if '-ssl' in r else 'http'
|
||||
endpoint = '/members' if '-server' in r else ''
|
||||
for host, port in self.get_srv_record('_etcd{0}._tcp.{1}'.format(r, srv)):
|
||||
url = '{0}://{1}:{2}{3}'.format(protocol, host, port, endpoint)
|
||||
url = uri(protocol, (host, port), endpoint)
|
||||
if endpoint:
|
||||
try:
|
||||
response = requests.get(url, timeout=self.read_timeout, verify=False)
|
||||
if response.ok:
|
||||
for member in response.json():
|
||||
response = requests_get(url, timeout=self.read_timeout, verify=False)
|
||||
if response.status < 400:
|
||||
for member in json.loads(response.data.decode('utf-8')):
|
||||
ret.extend(member['clientURLs'])
|
||||
break
|
||||
except RequestException:
|
||||
except Exception:
|
||||
logger.exception('GET %s', url)
|
||||
else:
|
||||
ret.append(url)
|
||||
@@ -249,15 +307,32 @@ class Client(etcd.Client):
|
||||
def _get_machines_cache_from_dns(self, host, port):
|
||||
"""One host might be resolved into multiple ip addresses. We will make list out of it"""
|
||||
if self.protocol == 'http':
|
||||
ret = []
|
||||
for af, _, _, _, sa in self._dns_resolver.resolve(host, port):
|
||||
host, port = sa[:2]
|
||||
if af == socket.AF_INET6:
|
||||
host = '[{0}]'.format(host)
|
||||
ret.append('{0}://{1}:{2}'.format(self.protocol, host, port))
|
||||
ret = map(lambda res: uri(self.protocol, res[-1][:2]), self._dns_resolver.resolve(host, port))
|
||||
if ret:
|
||||
return list(set(ret))
|
||||
return ['{0}://{1}:{2}'.format(self.protocol, host, port)]
|
||||
return [uri(self.protocol, (host, port))]
|
||||
|
||||
def _get_machines_cache_from_config(self):
|
||||
if 'proxy' in self._config:
|
||||
return [uri(self.protocol, (self._config['host'], self._config['port']))]
|
||||
|
||||
machines_cache = []
|
||||
if 'srv' in self._config:
|
||||
machines_cache = self._get_machines_cache_from_srv(self._config['srv'])
|
||||
|
||||
if not machines_cache and 'hosts' in self._config:
|
||||
machines_cache = list(self._config['hosts'])
|
||||
|
||||
if not machines_cache and 'host' in self._config:
|
||||
machines_cache = self._get_machines_cache_from_dns(self._config['host'], self._config['port'])
|
||||
return machines_cache
|
||||
|
||||
@staticmethod
|
||||
def _update_dns_cache(func, machines):
|
||||
for url in machines:
|
||||
r = urlparse(url)
|
||||
port = r.port or (443 if r.scheme == 'https' else 80)
|
||||
func(r.hostname, port)
|
||||
|
||||
def _load_machines_cache(self):
|
||||
"""This method should fill up `_machines_cache` from scratch.
|
||||
@@ -267,34 +342,52 @@ class Client(etcd.Client):
|
||||
|
||||
self._update_machines_cache = True
|
||||
|
||||
if 'srv' not in self._config and 'host' not in self._config:
|
||||
raise Exception('Neither srv nor host url are defined in etcd section of config')
|
||||
|
||||
if self._use_proxies:
|
||||
self._machines_cache = ['{0}://{1}:{2}'.format(self.protocol, self._config['host'], self._config['port'])]
|
||||
else:
|
||||
self._machines_cache = []
|
||||
|
||||
if 'srv' in self._config:
|
||||
self._machines_cache = self._get_machines_cache_from_srv(self._config['srv'])
|
||||
|
||||
if not self._machines_cache and 'host' in self._config:
|
||||
self._machines_cache = self._get_machines_cache_from_dns(self._config['host'], self._config['port'])
|
||||
if 'srv' not in self._config and 'host' not in self._config and 'hosts' not in self._config:
|
||||
raise Exception('Neither srv, hosts, host nor url are defined in etcd section of config')
|
||||
|
||||
machines_cache = self._get_machines_cache_from_config()
|
||||
# Can not bootstrap list of etcd-cluster members, giving up
|
||||
if not self._machines_cache:
|
||||
if not machines_cache:
|
||||
raise etcd.EtcdException
|
||||
|
||||
# After filling up initial list of machines_cache we should ask etcd-cluster about actual list
|
||||
self._base_uri = self._next_server()
|
||||
self._machines_cache = self.machines
|
||||
# enforce resolving dns name,they might get new ips
|
||||
self._update_dns_cache(self._dns_resolver.remove, machines_cache)
|
||||
|
||||
if self._base_uri in self._machines_cache:
|
||||
self._machines_cache.remove(self._base_uri)
|
||||
# The etcd cluster could change its topology over time and depending on how we resolve the initial
|
||||
# topology (list of hosts in the Patroni config or DNS records, A or SRV) we might get into the situation
|
||||
# the the real topology doesn't match anymore with the topology resolved from the configuration file.
|
||||
# In case if the "initial" topology is the same as before we will not override the `_machines_cache`.
|
||||
ret = set(machines_cache) != set(self._initial_machines_cache)
|
||||
if ret:
|
||||
self._initial_machines_cache = self._machines_cache = machines_cache
|
||||
|
||||
# After filling up the initial list of machines_cache we should ask etcd-cluster about actual list
|
||||
self._refresh_machines_cache(True)
|
||||
|
||||
self._update_machines_cache = False
|
||||
return ret
|
||||
|
||||
def _refresh_machines_cache(self, updating_cache=False):
|
||||
if self._use_proxies:
|
||||
self._machines_cache = self._get_machines_cache_from_config()
|
||||
else:
|
||||
try:
|
||||
self._machines_cache = self.machines
|
||||
except etcd.EtcdConnectionFailed:
|
||||
if updating_cache:
|
||||
raise etcd.EtcdException("Could not get the list of servers, "
|
||||
"maybe you provided the wrong "
|
||||
"host(s) to connect to?")
|
||||
return
|
||||
|
||||
if self._base_uri not in self._machines_cache:
|
||||
self.set_base_uri(self._machines_cache[0])
|
||||
self._machines_cache_updated = time.time()
|
||||
|
||||
def set_base_uri(self, value):
|
||||
logger.info('Selected new etcd server %s', value)
|
||||
self._base_uri = value
|
||||
|
||||
|
||||
class Etcd(AbstractDCS):
|
||||
|
||||
@@ -302,15 +395,15 @@ class Etcd(AbstractDCS):
|
||||
super(Etcd, self).__init__(config)
|
||||
self._ttl = int(config.get('ttl') or 30)
|
||||
self._retry = Retry(deadline=config['retry_timeout'], max_delay=1, max_tries=-1,
|
||||
retry_exceptions=(etcd.EtcdLeaderElectionInProgress,
|
||||
etcd.EtcdWatcherCleared,
|
||||
etcd.EtcdEventIndexCleared))
|
||||
retry_exceptions=(etcd.EtcdLeaderElectionInProgress, EtcdRaftInternal))
|
||||
self._client = self.get_etcd_client(config)
|
||||
self.__do_not_watch = False
|
||||
self._has_failed = False
|
||||
|
||||
def retry(self, *args, **kwargs):
|
||||
return self._retry.copy()(*args, **kwargs)
|
||||
retry = self._retry.copy()
|
||||
kwargs['retry'] = retry
|
||||
return retry(*args, **kwargs)
|
||||
|
||||
def _handle_exception(self, e, name='', do_sleep=False, raise_ex=None):
|
||||
if not self._has_failed:
|
||||
@@ -347,8 +440,20 @@ class Etcd(AbstractDCS):
|
||||
r = urlparse(config['url'])
|
||||
config.update({'protocol': r.scheme, 'host': r.hostname, 'port': r.port or 2379,
|
||||
'username': r.username, 'password': r.password})
|
||||
elif 'hosts' in config:
|
||||
hosts = config.pop('hosts')
|
||||
default_port = config.pop('port', 2379)
|
||||
protocol = config.get('protocol', 'http')
|
||||
|
||||
if isinstance(hosts, six.string_types):
|
||||
hosts = hosts.split(',')
|
||||
|
||||
config['hosts'] = []
|
||||
for value in hosts:
|
||||
if isinstance(value, six.string_types):
|
||||
config['hosts'].append(uri(protocol, split_host_port(value.strip(), default_port)))
|
||||
elif 'host' in config:
|
||||
host, port = (config['host'] + ':2379').split(':')[:2]
|
||||
host, port = split_host_port(config['host'], 2379)
|
||||
config['host'] = host
|
||||
if 'port' not in config:
|
||||
config['port'] = int(port)
|
||||
@@ -402,6 +507,8 @@ class Etcd(AbstractDCS):
|
||||
while not client:
|
||||
try:
|
||||
client = Client(config, dns_resolver)
|
||||
if 'use_proxies' in config and not client.machines:
|
||||
raise etcd.EtcdException
|
||||
except etcd.EtcdException:
|
||||
logger.info('waiting on etcd')
|
||||
time.sleep(5)
|
||||
@@ -413,6 +520,10 @@ class Etcd(AbstractDCS):
|
||||
self._ttl = ttl
|
||||
self._client.set_machines_cache_ttl(ttl*10)
|
||||
|
||||
@property
|
||||
def ttl(self):
|
||||
return self._ttl
|
||||
|
||||
def set_retry_timeout(self, retry_timeout):
|
||||
self._retry.deadline = retry_timeout
|
||||
self._client.set_read_timeout(retry_timeout)
|
||||
@@ -422,9 +533,10 @@ class Etcd(AbstractDCS):
|
||||
return Member.from_node(node.modifiedIndex, os.path.basename(node.key), node.ttl, node.value)
|
||||
|
||||
def _load_cluster(self):
|
||||
cluster = None
|
||||
try:
|
||||
result = self.retry(self._client.read, self.client_path(''), recursive=True)
|
||||
nodes = {os.path.relpath(node.key, result.key): node for node in result.leaves}
|
||||
nodes = {node.key[len(result.key):].lstrip('/'): node for node in result.leaves}
|
||||
|
||||
# get initialize flag
|
||||
initialize = nodes.get(self._INITIALIZE)
|
||||
@@ -434,6 +546,10 @@ class Etcd(AbstractDCS):
|
||||
config = nodes.get(self._CONFIG)
|
||||
config = config and ClusterConfig.from_node(config.modifiedIndex, config.value)
|
||||
|
||||
# get timeline history
|
||||
history = nodes.get(self._HISTORY)
|
||||
history = history and TimelineHistory.from_node(history.modifiedIndex, history.value)
|
||||
|
||||
# get last leader operation
|
||||
last_leader_operation = nodes.get(self._LEADER_OPTIME)
|
||||
last_leader_operation = 0 if last_leader_operation is None else int(last_leader_operation.value)
|
||||
@@ -458,20 +574,22 @@ class Etcd(AbstractDCS):
|
||||
sync = nodes.get(self._SYNC)
|
||||
sync = SyncState.from_node(sync and sync.modifiedIndex, sync and sync.value)
|
||||
|
||||
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync)
|
||||
cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
|
||||
except etcd.EtcdKeyNotFound:
|
||||
self._cluster = Cluster(None, None, None, None, [], None, None)
|
||||
cluster = Cluster(None, None, None, None, [], None, None, None)
|
||||
except Exception as e:
|
||||
self._handle_exception(e, 'get_cluster', raise_ex=EtcdError('Etcd is not responding properly'))
|
||||
self._has_failed = False
|
||||
return cluster
|
||||
|
||||
@catch_etcd_errors
|
||||
def touch_member(self, data, ttl=None, permanent=False):
|
||||
return self.retry(self._client.set, self.member_path, data, None if permanent else ttl or self._ttl)
|
||||
def touch_member(self, data, permanent=False):
|
||||
data = json.dumps(data, separators=(',', ':'))
|
||||
return self._client.set(self.member_path, data, None if permanent else self._ttl)
|
||||
|
||||
@catch_etcd_errors
|
||||
def take_leader(self):
|
||||
return self.retry(self._client.set, self.leader_path, self._name, self._ttl)
|
||||
return self.retry(self._client.write, self.leader_path, self._name, ttl=self._ttl)
|
||||
|
||||
def attempt_to_acquire_leader(self, permanent=False):
|
||||
try:
|
||||
@@ -499,15 +617,15 @@ class Etcd(AbstractDCS):
|
||||
return self._client.set(self.leader_optime_path, last_operation)
|
||||
|
||||
@catch_etcd_errors
|
||||
def update_leader(self):
|
||||
return self.retry(self._client.test_and_set, self.leader_path, self._name, self._name, self._ttl)
|
||||
def _update_leader(self):
|
||||
return self.retry(self._client.write, self.leader_path, self._name, prevValue=self._name, ttl=self._ttl)
|
||||
|
||||
@catch_etcd_errors
|
||||
def initialize(self, create_new=True, sysid=""):
|
||||
return self.retry(self._client.write, self.initialize_path, sysid, prevExist=(not create_new))
|
||||
|
||||
@catch_etcd_errors
|
||||
def delete_leader(self):
|
||||
def _delete_leader(self):
|
||||
return self._client.delete(self.leader_path, prevValue=self._name)
|
||||
|
||||
@catch_etcd_errors
|
||||
@@ -518,9 +636,13 @@ class Etcd(AbstractDCS):
|
||||
def delete_cluster(self):
|
||||
return self.retry(self._client.delete, self.client_path(''), recursive=True)
|
||||
|
||||
@catch_etcd_errors
|
||||
def set_history_value(self, value):
|
||||
return self._client.write(self.history_path, value)
|
||||
|
||||
@catch_etcd_errors
|
||||
def set_sync_state_value(self, value, index=None):
|
||||
return self._client.write(self.sync_path, value, prevIndex=index or 0)
|
||||
return self.retry(self._client.write, self.sync_path, value, prevIndex=index or 0)
|
||||
|
||||
@catch_etcd_errors
|
||||
def delete_sync_state(self, index=None):
|
||||
@@ -542,7 +664,6 @@ class Etcd(AbstractDCS):
|
||||
# than reestablishing http connection every time from every replica.
|
||||
return True
|
||||
except etcd.EtcdWatchTimedOut:
|
||||
self._client.http.clear()
|
||||
self._has_failed = False
|
||||
return False
|
||||
except (etcd.EtcdEventIndexCleared, etcd.EtcdWatcherCleared): # Watch failed
|
||||
@@ -557,3 +678,6 @@ class Etcd(AbstractDCS):
|
||||
return super(Etcd, self).watch(None, timeout)
|
||||
finally:
|
||||
self.event.clear()
|
||||
|
||||
|
||||
etcd.EtcdError.error_exceptions[300] = EtcdRaftInternal
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
import requests
|
||||
import time
|
||||
|
||||
from patroni.dcs.zookeeper import ZooKeeper
|
||||
from requests.exceptions import RequestException
|
||||
from patroni.request import get as requests_get
|
||||
from patroni.utils import uri
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -46,12 +47,11 @@ class ExhibitorEnsembleProvider(object):
|
||||
def _query_exhibitors(self, exhibitors):
|
||||
random.shuffle(exhibitors)
|
||||
for host in exhibitors:
|
||||
uri = 'http://{0}:{1}{2}'.format(host, self._exhibitor_port, self._uri_path)
|
||||
try:
|
||||
response = requests.get(uri, timeout=self.TIMEOUT)
|
||||
return response.json()
|
||||
except RequestException:
|
||||
pass
|
||||
response = requests_get(uri('http', (host, self._exhibitor_port), self._uri_path), timeout=self.TIMEOUT)
|
||||
return json.loads(response.data.decode('utf-8'))
|
||||
except Exception:
|
||||
logging.debug('Request to %s failed', host)
|
||||
return None
|
||||
|
||||
@property
|
||||
|
||||
@@ -0,0 +1,663 @@
|
||||
from __future__ import absolute_import
|
||||
import datetime
|
||||
import functools
|
||||
import json
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
|
||||
from kubernetes import client as k8s_client, config as k8s_config, watch as k8s_watch
|
||||
from urllib3 import Timeout
|
||||
from urllib3.exceptions import HTTPError
|
||||
from six.moves.http_client import HTTPException
|
||||
from threading import Condition, Lock, Thread
|
||||
|
||||
from . import AbstractDCS, Cluster, ClusterConfig, Failover, Leader, Member, SyncState, TimelineHistory
|
||||
from ..exceptions import DCSError
|
||||
from ..utils import deep_compare, Retry, RetryFailedError, tzutc, USER_AGENT
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class KubernetesError(DCSError):
|
||||
pass
|
||||
|
||||
|
||||
class KubernetesRetriableException(k8s_client.rest.ApiException):
|
||||
|
||||
def __init__(self, orig):
|
||||
super(KubernetesRetriableException, self).__init__(orig.status, orig.reason)
|
||||
self.body = orig.body
|
||||
self.headers = orig.headers
|
||||
|
||||
@property
|
||||
def sleeptime(self):
|
||||
try:
|
||||
return int(self.headers['retry-after'])
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
class CoreV1ApiProxy(object):
|
||||
|
||||
def __init__(self, use_endpoints=False):
|
||||
self._api = k8s_client.CoreV1Api()
|
||||
self._api.api_client.user_agent = USER_AGENT
|
||||
self._api.api_client.rest_client.pool_manager.connection_pool_kw['maxsize'] = 10
|
||||
self._request_timeout = None
|
||||
self._use_endpoints = bool(use_endpoints)
|
||||
|
||||
def configure_timeouts(self, loop_wait, retry_timeout, ttl):
|
||||
# Normally every loop_wait seconds we should have receive something from the socket.
|
||||
# If we didn't received anything after the loop_wait + retry_timeout it is a time
|
||||
# to start worrying (send keepalive messages). Finally, the connection should be
|
||||
# considered as dead if we received nothing from the socket after the ttl seconds.
|
||||
cnt = 3
|
||||
idle = int(loop_wait + retry_timeout)
|
||||
intvl = max(1, int(float(ttl - idle) / cnt))
|
||||
self._api.api_client.rest_client.pool_manager.connection_pool_kw['socket_options'] = [
|
||||
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
|
||||
(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle),
|
||||
(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, intvl),
|
||||
(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, cnt),
|
||||
(socket.IPPROTO_TCP, 18, int(ttl * 1000)) # TCP_USER_TIMEOUT
|
||||
]
|
||||
self._request_timeout = (1, retry_timeout / 3.0)
|
||||
|
||||
def __getattr__(self, func):
|
||||
if func.endswith('_kind'):
|
||||
func = func[:-4] + ('endpoints' if self._use_endpoints else 'config_map')
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
if '_request_timeout' not in kwargs:
|
||||
kwargs['_request_timeout'] = self._request_timeout
|
||||
try:
|
||||
return getattr(self._api, func)(*args, **kwargs)
|
||||
except k8s_client.rest.ApiException as e:
|
||||
if e.status in (500, 503, 504) or e.headers and 'retry-after' in e.headers: # XXX
|
||||
raise KubernetesRetriableException(e)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
@property
|
||||
def use_endpoints(self):
|
||||
return self._use_endpoints
|
||||
|
||||
|
||||
def catch_kubernetes_errors(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except k8s_client.rest.ApiException as e:
|
||||
if e.status == 403:
|
||||
logger.exception('Permission denied')
|
||||
elif e.status != 409: # Object exists or conflict in resource_version
|
||||
logger.exception('Unexpected error from Kubernetes API')
|
||||
return False
|
||||
except (RetryFailedError, HTTPException, HTTPError, socket.error, socket.timeout):
|
||||
return False
|
||||
return wrapper
|
||||
|
||||
|
||||
class ObjectCache(Thread):
|
||||
|
||||
def __init__(self, dcs, func, retry, condition, name=None):
|
||||
Thread.__init__(self)
|
||||
self.daemon = True
|
||||
self._api_client = k8s_client.ApiClient()
|
||||
self._dcs = dcs
|
||||
self._func = func
|
||||
self._retry = retry
|
||||
self._condition = condition
|
||||
self._name = name # name of this pod
|
||||
self._is_ready = False
|
||||
self._object_cache = {}
|
||||
self._object_cache_lock = Lock()
|
||||
self._annotations_map = {self._dcs.leader_path: self._dcs._LEADER, self._dcs.config_path: self._dcs._CONFIG}
|
||||
self.start()
|
||||
|
||||
def _list(self):
|
||||
try:
|
||||
return self._func(_request_timeout=(self._retry.deadline, Timeout.DEFAULT_TIMEOUT))
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
raise
|
||||
|
||||
def _watch(self, resource_version):
|
||||
return self._func(_request_timeout=(self._retry.deadline, Timeout.DEFAULT_TIMEOUT),
|
||||
_preload_content=False, watch=True, resource_version=resource_version)
|
||||
|
||||
def set(self, name, value):
|
||||
with self._object_cache_lock:
|
||||
old_value = self._object_cache.get(name)
|
||||
ret = not old_value or int(old_value.metadata.resource_version) < int(value.metadata.resource_version)
|
||||
if ret:
|
||||
self._object_cache[name] = value
|
||||
return ret, old_value
|
||||
|
||||
def delete(self, name, resource_version):
|
||||
with self._object_cache_lock:
|
||||
old_value = self._object_cache.get(name)
|
||||
ret = old_value and int(old_value.metadata.resource_version) < int(resource_version)
|
||||
if ret:
|
||||
del self._object_cache[name]
|
||||
return not old_value or ret, old_value
|
||||
|
||||
def copy(self):
|
||||
with self._object_cache_lock:
|
||||
return self._object_cache.copy()
|
||||
|
||||
def get(self, name):
|
||||
with self._object_cache_lock:
|
||||
return self._object_cache.get(name)
|
||||
|
||||
def _build_cache(self):
|
||||
objects = self._list()
|
||||
return_type = 'V1' + objects.kind[:-4]
|
||||
with self._object_cache_lock:
|
||||
self._object_cache = {item.metadata.name: item for item in objects.items}
|
||||
with self._condition:
|
||||
self._is_ready = True
|
||||
self._condition.notify()
|
||||
|
||||
response = self._watch(objects.metadata.resource_version)
|
||||
try:
|
||||
for line in k8s_watch.watch.iter_resp_lines(response):
|
||||
event = json.loads(line)
|
||||
obj = event['object']
|
||||
if obj.get('code') == 410:
|
||||
break
|
||||
|
||||
ev_type = event['type']
|
||||
name = obj['metadata']['name']
|
||||
|
||||
if ev_type in ('ADDED', 'MODIFIED'):
|
||||
obj = k8s_watch.watch.SimpleNamespace(data=json.dumps(obj))
|
||||
obj = self._api_client.deserialize(obj, return_type)
|
||||
success, old_value = self.set(name, obj)
|
||||
if success:
|
||||
new_value = (obj.metadata.annotations or {}).get(self._annotations_map.get(name))
|
||||
elif ev_type == 'DELETED':
|
||||
success, old_value = self.delete(name, obj['metadata']['resourceVersion'])
|
||||
new_value = None
|
||||
else:
|
||||
logger.warning('Unexpected event type: %s', ev_type)
|
||||
continue
|
||||
|
||||
if success and return_type != 'V1Pod':
|
||||
if old_value:
|
||||
old_value = (old_value.metadata.annotations or {}).get(self._annotations_map.get(name))
|
||||
|
||||
value_changed = old_value != new_value and \
|
||||
(name != self._dcs.config_path or old_value is not None and new_value is not None)
|
||||
|
||||
if value_changed:
|
||||
logger.debug('%s changed from %s to %s', name, old_value, new_value)
|
||||
|
||||
# Do not wake up HA loop if we run as leader and received leader object update event
|
||||
if value_changed or name == self._dcs.leader_path and self._name != new_value:
|
||||
self._dcs.event.set()
|
||||
finally:
|
||||
with self._condition:
|
||||
self._is_ready = False
|
||||
response.close()
|
||||
response.release_conn()
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
try:
|
||||
self._build_cache()
|
||||
except Exception as e:
|
||||
with self._condition:
|
||||
self._is_ready = False
|
||||
logger.error('ObjectCache.run %r', e)
|
||||
|
||||
def is_ready(self):
|
||||
"""Must be called only when holding the lock on `_condition`"""
|
||||
return self._is_ready
|
||||
|
||||
|
||||
class Kubernetes(AbstractDCS):
|
||||
|
||||
def __init__(self, config):
|
||||
self._labels = config['labels']
|
||||
self._labels[config.get('scope_label', 'cluster-name')] = config['scope']
|
||||
self._label_selector = ','.join('{0}={1}'.format(k, v) for k, v in self._labels.items())
|
||||
self._namespace = config.get('namespace') or 'default'
|
||||
self._role_label = config.get('role_label', 'role')
|
||||
config['namespace'] = ''
|
||||
super(Kubernetes, self).__init__(config)
|
||||
self._retry = Retry(deadline=config['retry_timeout'], max_delay=1, max_tries=-1,
|
||||
retry_exceptions=(KubernetesRetriableException, HTTPException,
|
||||
HTTPError, socket.error, socket.timeout))
|
||||
self._ttl = None
|
||||
try:
|
||||
k8s_config.load_incluster_config()
|
||||
except k8s_config.ConfigException:
|
||||
k8s_config.load_kube_config(context=config.get('context', 'local'))
|
||||
|
||||
self.__my_pod = None
|
||||
self.__ips = [] if config.get('patronictl') else [config.get('pod_ip')]
|
||||
self.__ports = []
|
||||
for p in config.get('ports', [{}]):
|
||||
port = {'port': int(p.get('port', '5432'))}
|
||||
port.update({n: p[n] for n in ('name', 'protocol') if p.get(n)})
|
||||
self.__ports.append(k8s_client.V1EndpointPort(**port))
|
||||
|
||||
self._api = CoreV1ApiProxy(config.get('use_endpoints'))
|
||||
self._should_create_config_service = self._api.use_endpoints
|
||||
self.reload_config(config)
|
||||
# leader_observed_record, leader_resource_version, and leader_observed_time are used only for leader race!
|
||||
self._leader_observed_record = {}
|
||||
self._leader_observed_time = None
|
||||
self._leader_resource_version = None
|
||||
self.__do_not_watch = False
|
||||
|
||||
self._condition = Condition()
|
||||
|
||||
pods_func = functools.partial(self._api.list_namespaced_pod, self._namespace,
|
||||
label_selector=self._label_selector)
|
||||
self._pods = ObjectCache(self, pods_func, self._retry, self._condition)
|
||||
|
||||
kinds_func = functools.partial(self._api.list_namespaced_kind, self._namespace,
|
||||
label_selector=self._label_selector)
|
||||
self._kinds = ObjectCache(self, kinds_func, self._retry, self._condition, self._name)
|
||||
|
||||
def retry(self, *args, **kwargs):
|
||||
return self._retry.copy()(*args, **kwargs)
|
||||
|
||||
def client_path(self, path):
|
||||
return super(Kubernetes, self).client_path(path)[1:].replace('/', '-')
|
||||
|
||||
@property
|
||||
def leader_path(self):
|
||||
return self._base_path[1:] if self._api.use_endpoints else super(Kubernetes, self).leader_path
|
||||
|
||||
def set_ttl(self, ttl):
|
||||
ttl = int(ttl)
|
||||
self.__do_not_watch = self._ttl != ttl
|
||||
self._ttl = ttl
|
||||
|
||||
@property
|
||||
def ttl(self):
|
||||
return self._ttl
|
||||
|
||||
def set_retry_timeout(self, retry_timeout):
|
||||
self._retry.deadline = retry_timeout
|
||||
|
||||
def reload_config(self, config):
|
||||
super(Kubernetes, self).reload_config(config)
|
||||
self._api.configure_timeouts(self.loop_wait, self._retry.deadline, self.ttl)
|
||||
|
||||
@staticmethod
|
||||
def member(pod):
|
||||
annotations = pod.metadata.annotations or {}
|
||||
member = Member.from_node(pod.metadata.resource_version, pod.metadata.name, None, annotations.get('status', ''))
|
||||
member.data['pod_labels'] = pod.metadata.labels
|
||||
return member
|
||||
|
||||
def _wait_caches(self):
|
||||
stop_time = time.time() + self._retry.deadline
|
||||
while not (self._pods.is_ready() and self._kinds.is_ready()):
|
||||
timeout = stop_time - time.time()
|
||||
if timeout <= 0:
|
||||
raise RetryFailedError('Exceeded retry deadline')
|
||||
self._condition.wait(timeout)
|
||||
|
||||
def _load_cluster(self):
|
||||
try:
|
||||
with self._condition:
|
||||
self._wait_caches()
|
||||
|
||||
members = [self.member(pod) for pod in self._pods.copy().values()]
|
||||
nodes = self._kinds.copy()
|
||||
|
||||
config = nodes.get(self.config_path)
|
||||
metadata = config and config.metadata
|
||||
annotations = metadata and metadata.annotations or {}
|
||||
|
||||
# get initialize flag
|
||||
initialize = annotations.get(self._INITIALIZE)
|
||||
|
||||
# get global dynamic configuration
|
||||
config = ClusterConfig.from_node(metadata and metadata.resource_version,
|
||||
annotations.get(self._CONFIG) or '{}',
|
||||
metadata.resource_version if self._CONFIG in annotations else 0)
|
||||
|
||||
# get timeline history
|
||||
history = TimelineHistory.from_node(metadata and metadata.resource_version,
|
||||
annotations.get(self._HISTORY) or '[]')
|
||||
|
||||
leader = nodes.get(self.leader_path)
|
||||
metadata = leader and leader.metadata
|
||||
self._leader_resource_version = metadata.resource_version if metadata else None
|
||||
annotations = metadata and metadata.annotations or {}
|
||||
|
||||
# get last leader operation
|
||||
last_leader_operation = annotations.get(self._OPTIME)
|
||||
last_leader_operation = 0 if last_leader_operation is None else int(last_leader_operation)
|
||||
|
||||
# get leader
|
||||
leader_record = {n: annotations.get(n) for n in (self._LEADER, 'acquireTime',
|
||||
'ttl', 'renewTime', 'transitions') if n in annotations}
|
||||
if (leader_record or self._leader_observed_record) and leader_record != self._leader_observed_record:
|
||||
self._leader_observed_record = leader_record
|
||||
self._leader_observed_time = time.time()
|
||||
|
||||
leader = leader_record.get(self._LEADER)
|
||||
try:
|
||||
ttl = int(leader_record.get('ttl')) or self._ttl
|
||||
except (TypeError, ValueError):
|
||||
ttl = self._ttl
|
||||
|
||||
if not metadata or not self._leader_observed_time or self._leader_observed_time + ttl < time.time():
|
||||
leader = None
|
||||
|
||||
if metadata:
|
||||
member = Member(-1, leader, None, {})
|
||||
member = ([m for m in members if m.name == leader] or [member])[0]
|
||||
leader = Leader(metadata.resource_version, None, member)
|
||||
|
||||
# failover key
|
||||
failover = nodes.get(self.failover_path)
|
||||
metadata = failover and failover.metadata
|
||||
failover = Failover.from_node(metadata and metadata.resource_version,
|
||||
metadata and (metadata.annotations or {}).copy())
|
||||
|
||||
# get synchronization state
|
||||
sync = nodes.get(self.sync_path)
|
||||
metadata = sync and sync.metadata
|
||||
sync = SyncState.from_node(metadata and metadata.resource_version, metadata and metadata.annotations)
|
||||
|
||||
return Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
|
||||
except Exception:
|
||||
logger.exception('get_cluster')
|
||||
raise KubernetesError('Kubernetes API is not responding properly')
|
||||
|
||||
@staticmethod
|
||||
def compare_ports(p1, p2):
|
||||
return p1.name == p2.name and p1.port == p2.port and (p1.protocol or 'TCP') == (p2.protocol or 'TCP')
|
||||
|
||||
@staticmethod
|
||||
def subsets_changed(last_observed_subsets, ip, ports):
|
||||
"""
|
||||
>>> Kubernetes.subsets_changed([], None, [])
|
||||
True
|
||||
>>> ip = '1.2.3.4'
|
||||
>>> a = [k8s_client.V1EndpointAddress(ip=ip)]
|
||||
>>> s = [k8s_client.V1EndpointSubset(addresses=a)]
|
||||
>>> Kubernetes.subsets_changed(s, '1.2.3.5', [])
|
||||
True
|
||||
>>> s = [k8s_client.V1EndpointSubset(addresses=a, ports=[k8s_client.V1EndpointPort(protocol='TCP', port=1)])]
|
||||
>>> Kubernetes.subsets_changed(s, '1.2.3.4', [k8s_client.V1EndpointPort(port=5432)])
|
||||
True
|
||||
>>> p1 = k8s_client.V1EndpointPort(name='port1', port=1)
|
||||
>>> p2 = k8s_client.V1EndpointPort(name='port2', port=2)
|
||||
>>> p3 = k8s_client.V1EndpointPort(name='port3', port=3)
|
||||
>>> s = [k8s_client.V1EndpointSubset(addresses=a, ports=[p1, p2])]
|
||||
>>> Kubernetes.subsets_changed(s, ip, [p2, p3])
|
||||
True
|
||||
>>> s2 = [k8s_client.V1EndpointSubset(addresses=a, ports=[p2, p1])]
|
||||
>>> Kubernetes.subsets_changed(s, ip, [p2, p1])
|
||||
False
|
||||
"""
|
||||
|
||||
if len(last_observed_subsets) != 1:
|
||||
return True
|
||||
if len(last_observed_subsets[0].addresses or []) != 1 or \
|
||||
last_observed_subsets[0].addresses[0].ip != ip or \
|
||||
len(last_observed_subsets[0].ports) != len(ports):
|
||||
return True
|
||||
if len(ports) == 1:
|
||||
return not Kubernetes.compare_ports(last_observed_subsets[0].ports[0], ports[0])
|
||||
observed_ports = {p.name: p for p in last_observed_subsets[0].ports}
|
||||
for p in ports:
|
||||
if p.name not in observed_ports or not Kubernetes.compare_ports(p, observed_ports.pop(p.name)):
|
||||
return True
|
||||
return False
|
||||
|
||||
def __target_ref(self, leader_ip, latest_subsets, pod):
|
||||
# we want to re-use existing target_ref if possible
|
||||
for subset in latest_subsets:
|
||||
for address in subset.addresses or []:
|
||||
if address.ip == leader_ip and address.target_ref and address.target_ref.name == self._name:
|
||||
return address.target_ref
|
||||
return k8s_client.V1ObjectReference(kind='Pod', uid=pod.metadata.uid, namespace=self._namespace,
|
||||
name=self._name, resource_version=pod.metadata.resource_version)
|
||||
|
||||
def _map_subsets(self, endpoints, ips):
|
||||
leader = self._kinds.get(self.leader_path)
|
||||
latest_subsets = leader and leader.subsets or []
|
||||
if not ips:
|
||||
# We want to have subsets empty
|
||||
if latest_subsets:
|
||||
endpoints['subsets'] = []
|
||||
return
|
||||
|
||||
pod = self._pods.get(self._name)
|
||||
leader_ip = ips[0] or pod and pod.status.pod_ip
|
||||
# don't touch subsets if our (leader) ip is unknown or subsets is valid
|
||||
if leader_ip and self.subsets_changed(latest_subsets, leader_ip, self.__ports):
|
||||
kwargs = {'hostname': pod.spec.hostname, 'node_name': pod.spec.node_name,
|
||||
'target_ref': self.__target_ref(leader_ip, latest_subsets, pod)} if pod else {}
|
||||
address = k8s_client.V1EndpointAddress(ip=leader_ip, **kwargs)
|
||||
endpoints['subsets'] = [k8s_client.V1EndpointSubset(addresses=[address], ports=self.__ports)]
|
||||
|
||||
def _patch_or_create(self, name, annotations, resource_version=None, patch=False, retry=None, ips=None):
|
||||
metadata = {'namespace': self._namespace, 'name': name, 'labels': self._labels, 'annotations': annotations}
|
||||
if patch or resource_version:
|
||||
if resource_version is not None:
|
||||
metadata['resource_version'] = resource_version
|
||||
func = functools.partial(self._api.patch_namespaced_kind, name)
|
||||
else:
|
||||
func = functools.partial(self._api.create_namespaced_kind)
|
||||
# skip annotations with null values
|
||||
metadata['annotations'] = {k: v for k, v in metadata['annotations'].items() if v is not None}
|
||||
|
||||
metadata = k8s_client.V1ObjectMeta(**metadata)
|
||||
if ips is not None and self._api.use_endpoints:
|
||||
endpoints = {'metadata': metadata}
|
||||
self._map_subsets(endpoints, ips)
|
||||
body = k8s_client.V1Endpoints(**endpoints)
|
||||
else:
|
||||
body = k8s_client.V1ConfigMap(metadata=metadata)
|
||||
ret = retry(func, self._namespace, body) if retry else func(self._namespace, body)
|
||||
if ret:
|
||||
self._kinds.set(name, ret)
|
||||
return ret
|
||||
|
||||
@catch_kubernetes_errors
|
||||
def patch_or_create(self, name, annotations, resource_version=None, patch=False, retry=True, ips=None):
|
||||
if retry is True:
|
||||
retry = self.retry
|
||||
return self._patch_or_create(name, annotations, resource_version, patch, retry, ips)
|
||||
|
||||
def patch_or_create_config(self, annotations, resource_version=None, patch=False, retry=True):
|
||||
# SCOPE-config endpoint requires corresponding service otherwise it might be "cleaned" by k8s master
|
||||
if self._api.use_endpoints and not patch and not resource_version:
|
||||
self._should_create_config_service = True
|
||||
self._create_config_service()
|
||||
return self.patch_or_create(self.config_path, annotations, resource_version, patch, retry)
|
||||
|
||||
def _create_config_service(self):
|
||||
metadata = k8s_client.V1ObjectMeta(namespace=self._namespace, name=self.config_path, labels=self._labels)
|
||||
body = k8s_client.V1Service(metadata=metadata, spec=k8s_client.V1ServiceSpec(cluster_ip='None'))
|
||||
try:
|
||||
if not self._api.create_namespaced_service(self._namespace, body):
|
||||
return
|
||||
except Exception as e:
|
||||
if not isinstance(e, k8s_client.rest.ApiException) or e.status != 409: # Service already exists
|
||||
return logger.exception('create_config_service failed')
|
||||
self._should_create_config_service = False
|
||||
|
||||
def _write_leader_optime(self, last_operation):
|
||||
"""Unused"""
|
||||
|
||||
def _update_leader(self):
|
||||
"""Unused"""
|
||||
|
||||
def _update_leader_with_retry(self, annotations, resource_version, ips):
|
||||
retry = self._retry.copy()
|
||||
|
||||
def _retry(*args, **kwargs):
|
||||
return retry(*args, **kwargs)
|
||||
|
||||
try:
|
||||
return self._patch_or_create(self.leader_path, annotations, resource_version, ips=ips, retry=_retry)
|
||||
except k8s_client.rest.ApiException as e:
|
||||
if e.status == 409:
|
||||
logger.warning('Concurrent update of %s', self.leader_path)
|
||||
else:
|
||||
logger.exception('Permission denied' if e.status == 403 else 'Unexpected error from Kubernetes API')
|
||||
return False
|
||||
except RetryFailedError:
|
||||
return False
|
||||
|
||||
deadline = retry.stoptime - time.time()
|
||||
if deadline < 2:
|
||||
return False
|
||||
|
||||
retry.sleep_func(1) # Give a chance for ObjectCache to receive the latest version
|
||||
|
||||
kind = self._kinds.get(self.leader_path)
|
||||
kind_annotations = kind and kind.metadata.annotations or {}
|
||||
kind_resource_version = kind and kind.metadata.resource_version
|
||||
|
||||
# There is different leader or resource_version in cache didn't change
|
||||
if kind and (kind_annotations.get(self._LEADER) != self._name or kind_resource_version == resource_version):
|
||||
return False
|
||||
|
||||
retry.deadline = deadline - 1 # Update deadline and retry
|
||||
return self.patch_or_create(self.leader_path, annotations, kind_resource_version, ips=ips, retry=_retry)
|
||||
|
||||
def update_leader(self, last_operation, access_is_restricted=False):
|
||||
kind = self._kinds.get(self.leader_path)
|
||||
kind_annotations = kind and kind.metadata.annotations or {}
|
||||
|
||||
if kind and kind_annotations.get(self._LEADER) != self._name:
|
||||
return False
|
||||
|
||||
now = datetime.datetime.now(tzutc).isoformat()
|
||||
leader_observed_record = kind_annotations or self._leader_observed_record
|
||||
annotations = {self._LEADER: self._name, 'ttl': str(self._ttl), 'renewTime': now,
|
||||
'acquireTime': leader_observed_record.get('acquireTime') or now,
|
||||
'transitions': leader_observed_record.get('transitions') or '0'}
|
||||
if last_operation:
|
||||
annotations[self._OPTIME] = last_operation
|
||||
|
||||
resource_version = kind and kind.metadata.resource_version
|
||||
ips = [] if access_is_restricted else self.__ips
|
||||
return self._update_leader_with_retry(annotations, resource_version, ips)
|
||||
|
||||
def attempt_to_acquire_leader(self, permanent=False):
|
||||
now = datetime.datetime.now(tzutc).isoformat()
|
||||
annotations = {self._LEADER: self._name, 'ttl': str(sys.maxsize if permanent else self._ttl),
|
||||
'renewTime': now, 'acquireTime': now, 'transitions': '0'}
|
||||
if self._leader_observed_record:
|
||||
try:
|
||||
transitions = int(self._leader_observed_record.get('transitions'))
|
||||
except (TypeError, ValueError):
|
||||
transitions = 0
|
||||
|
||||
if self._leader_observed_record.get(self._LEADER) != self._name:
|
||||
transitions += 1
|
||||
else:
|
||||
annotations['acquireTime'] = self._leader_observed_record.get('acquireTime') or now
|
||||
annotations['transitions'] = str(transitions)
|
||||
ips = [] if self._api.use_endpoints else None
|
||||
ret = self.patch_or_create(self.leader_path, annotations, self._leader_resource_version, ips=ips)
|
||||
if not ret:
|
||||
logger.info('Could not take out TTL lock')
|
||||
return ret
|
||||
|
||||
def take_leader(self):
|
||||
return self.attempt_to_acquire_leader()
|
||||
|
||||
def set_failover_value(self, value, index=None):
|
||||
"""Unused"""
|
||||
|
||||
def manual_failover(self, leader, candidate, scheduled_at=None, index=None):
|
||||
annotations = {'leader': leader or None, 'member': candidate or None,
|
||||
'scheduled_at': scheduled_at and scheduled_at.isoformat()}
|
||||
patch = bool(self.cluster and isinstance(self.cluster.failover, Failover) and self.cluster.failover.index)
|
||||
return self.patch_or_create(self.failover_path, annotations, index, bool(index or patch), False)
|
||||
|
||||
@property
|
||||
def _config_resource_version(self):
|
||||
config = self._kinds.get(self.config_path)
|
||||
return config and config.metadata.resource_version
|
||||
|
||||
def set_config_value(self, value, index=None):
|
||||
return self.patch_or_create_config({self._CONFIG: value}, index, bool(self._config_resource_version), False)
|
||||
|
||||
@catch_kubernetes_errors
|
||||
def touch_member(self, data, permanent=False):
|
||||
cluster = self.cluster
|
||||
if cluster and cluster.leader and cluster.leader.name == self._name:
|
||||
role = 'promoted' if data['role'] in ('replica', 'promoted') else 'master'
|
||||
elif data['state'] == 'running' and data['role'] != 'master':
|
||||
role = data['role']
|
||||
else:
|
||||
role = None
|
||||
|
||||
member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
|
||||
pod_labels = member and member.data.pop('pod_labels', None)
|
||||
ret = pod_labels is not None and pod_labels.get(self._role_label) == role and deep_compare(data, member.data)
|
||||
|
||||
if not ret:
|
||||
metadata = {'namespace': self._namespace, 'name': self._name, 'labels': {self._role_label: role},
|
||||
'annotations': {'status': json.dumps(data, separators=(',', ':'))}}
|
||||
body = k8s_client.V1Pod(metadata=k8s_client.V1ObjectMeta(**metadata))
|
||||
ret = self._api.patch_namespaced_pod(self._name, self._namespace, body)
|
||||
if ret:
|
||||
self._pods.set(self._name, ret)
|
||||
if self._should_create_config_service:
|
||||
self._create_config_service()
|
||||
return ret
|
||||
|
||||
def initialize(self, create_new=True, sysid=""):
|
||||
cluster = self.cluster
|
||||
resource_version = cluster.config.index if cluster and cluster.config and cluster.config.index else None
|
||||
return self.patch_or_create_config({self._INITIALIZE: sysid}, resource_version)
|
||||
|
||||
def _delete_leader(self):
|
||||
"""Unused"""
|
||||
|
||||
def delete_leader(self, last_operation=None):
|
||||
kind = self._kinds.get(self.leader_path)
|
||||
if kind and (kind.metadata.annotations or {}).get(self._LEADER) == self._name:
|
||||
annotations = {self._LEADER: None}
|
||||
if last_operation:
|
||||
annotations[self._OPTIME] = last_operation
|
||||
self.patch_or_create(self.leader_path, annotations, kind.metadata.resource_version, True, False, [])
|
||||
self.reset_cluster()
|
||||
|
||||
def cancel_initialization(self):
|
||||
self.patch_or_create_config({self._INITIALIZE: None}, self._config_resource_version, True)
|
||||
|
||||
@catch_kubernetes_errors
|
||||
def delete_cluster(self):
|
||||
self.retry(self._api.delete_collection_namespaced_kind, self._namespace, label_selector=self._label_selector)
|
||||
|
||||
def set_history_value(self, value):
|
||||
return self.patch_or_create_config({self._HISTORY: value}, None, bool(self._config_resource_version), False)
|
||||
|
||||
def set_sync_state_value(self, value, index=None):
|
||||
"""Unused"""
|
||||
|
||||
def write_sync_state(self, leader, sync_standby, index=None):
|
||||
return self.patch_or_create(self.sync_path, self.sync_state(leader, sync_standby), index, False)
|
||||
|
||||
def delete_sync_state(self, index=None):
|
||||
return self.write_sync_state(None, None, index)
|
||||
|
||||
def watch(self, leader_index, timeout):
|
||||
if self.__do_not_watch:
|
||||
self.__do_not_watch = False
|
||||
return True
|
||||
|
||||
try:
|
||||
return super(Kubernetes, self).watch(None, timeout + 0.5)
|
||||
finally:
|
||||
self.event.clear()
|
||||
+90
-68
@@ -1,10 +1,14 @@
|
||||
import json
|
||||
import logging
|
||||
import select
|
||||
import time
|
||||
|
||||
from kazoo.client import KazooClient, KazooState
|
||||
from kazoo.client import KazooClient, KazooState, KazooRetry
|
||||
from kazoo.exceptions import NoNodeError, NodeExistsError
|
||||
from kazoo.handlers.threading import SequentialThreadingHandler
|
||||
from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState
|
||||
from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState, TimelineHistory
|
||||
from patroni.exceptions import DCSError
|
||||
from patroni.utils import deep_compare
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -34,12 +38,21 @@ class PatroniSequentialThreadingHandler(SequentialThreadingHandler):
|
||||
`connect_timeout` (negotiated session timeout) as the second element."""
|
||||
|
||||
args = list(args)
|
||||
if len(args) == 1:
|
||||
if len(args) == 0: # kazoo 2.6.0 slightly changed the way how it calls create_connection method
|
||||
kwargs['timeout'] = max(self._connect_timeout, kwargs.get('timeout', self._connect_timeout*10)/10.0)
|
||||
elif len(args) == 1:
|
||||
args.append(self._connect_timeout)
|
||||
else:
|
||||
args[1] = max(self._connect_timeout, args[1]/10.0)
|
||||
return super(PatroniSequentialThreadingHandler, self).create_connection(*args, **kwargs)
|
||||
|
||||
def select(self, *args, **kwargs):
|
||||
"""Python3 raises `ValueError` if socket is closed, because fd == -1"""
|
||||
try:
|
||||
return super(PatroniSequentialThreadingHandler, self).select(*args, **kwargs)
|
||||
except ValueError as e:
|
||||
raise select.error(9, str(e))
|
||||
|
||||
|
||||
class ZooKeeper(AbstractDCS):
|
||||
|
||||
@@ -51,11 +64,11 @@ class ZooKeeper(AbstractDCS):
|
||||
hosts = ','.join(hosts)
|
||||
|
||||
self._client = KazooClient(hosts, handler=PatroniSequentialThreadingHandler(config['retry_timeout']),
|
||||
timeout=config['ttl'], connection_retry={'max_delay': 1, 'max_tries': -1},
|
||||
command_retry={'deadline': config['retry_timeout'], 'max_delay': 1, 'max_tries': -1})
|
||||
timeout=config['ttl'], connection_retry=KazooRetry(max_delay=1, max_tries=-1,
|
||||
sleep_func=time.sleep), command_retry=KazooRetry(deadline=config['retry_timeout'],
|
||||
max_delay=1, max_tries=-1, sleep_func=time.sleep))
|
||||
self._client.add_listener(self.session_listener)
|
||||
|
||||
self._my_member_data = None
|
||||
self._fetch_cluster = True
|
||||
|
||||
self._orig_kazoo_connect = self._client._connection._connect
|
||||
@@ -63,7 +76,7 @@ class ZooKeeper(AbstractDCS):
|
||||
|
||||
self._client.start()
|
||||
|
||||
def _kazoo_connect(self, host, port):
|
||||
def _kazoo_connect(self, *args):
|
||||
"""Kazoo is using Ping's to determine health of connection to zookeeper. If there is no
|
||||
response on Ping after Ping interval (1/2 from read_timeout) it will consider current
|
||||
connection dead and try to connect to another node. Without this "magic" it was taking
|
||||
@@ -75,7 +88,7 @@ class ZooKeeper(AbstractDCS):
|
||||
than loop_wait, because we can spend up to 2 seconds when calling `touch_member()` and
|
||||
`write_leader_optime()` methods, which also may hang..."""
|
||||
|
||||
ret = self._orig_kazoo_connect(host, port)
|
||||
ret = self._orig_kazoo_connect(*args)
|
||||
return max(self.loop_wait - 2, 2)*1000, ret[1]
|
||||
|
||||
def session_listener(self, state):
|
||||
@@ -113,8 +126,13 @@ class ZooKeeper(AbstractDCS):
|
||||
self._client.restart()
|
||||
return True
|
||||
|
||||
@property
|
||||
def ttl(self):
|
||||
return self._client._session_timeout
|
||||
|
||||
def set_retry_timeout(self, retry_timeout):
|
||||
self._client._retry.deadline = retry_timeout
|
||||
retry = self._client.retry if isinstance(self._client.retry, KazooRetry) else self._client._retry
|
||||
retry.deadline = retry_timeout
|
||||
|
||||
def get_node(self, key, watch=None):
|
||||
try:
|
||||
@@ -156,6 +174,10 @@ class ZooKeeper(AbstractDCS):
|
||||
config = self.get_node(self.config_path, watch=self.cluster_watcher) if self._CONFIG in nodes else None
|
||||
config = config and ClusterConfig.from_node(config[1].version, config[0], config[1].mzxid)
|
||||
|
||||
# get timeline history
|
||||
history = self.get_node(self.history_path, watch=self.cluster_watcher) if self._HISTORY in nodes else None
|
||||
history = history and TimelineHistory.from_node(history[1].mzxid, history[0])
|
||||
|
||||
# get last leader operation
|
||||
last_leader_operation = self._OPTIME in nodes and self._fetch_cluster and self.get_node(self.leader_optime_path)
|
||||
last_leader_operation = last_leader_operation and int(last_leader_operation[0]) or 0
|
||||
@@ -188,84 +210,101 @@ class ZooKeeper(AbstractDCS):
|
||||
failover = self.get_node(self.failover_path, watch=self.cluster_watcher) if self._FAILOVER in nodes else None
|
||||
failover = failover and Failover.from_node(failover[1].version, failover[0])
|
||||
|
||||
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync)
|
||||
return Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
|
||||
|
||||
def _load_cluster(self):
|
||||
if self._fetch_cluster or self._cluster is None:
|
||||
cluster = self.cluster
|
||||
if self._fetch_cluster or cluster is None:
|
||||
try:
|
||||
self._client.retry(self._inner_load_cluster)
|
||||
cluster = self._client.retry(self._inner_load_cluster)
|
||||
except Exception:
|
||||
logger.exception('get_cluster')
|
||||
self.cluster_watcher(None)
|
||||
raise ZooKeeperError('ZooKeeper in not responding properly')
|
||||
return cluster
|
||||
|
||||
def _create(self, path, value, **kwargs):
|
||||
def _bypass_caches(self):
|
||||
self._fetch_cluster = True
|
||||
|
||||
def _create(self, path, value, retry=False, ephemeral=False):
|
||||
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
|
||||
except:
|
||||
return False
|
||||
except Exception:
|
||||
logger.exception('Failed to create %s', path)
|
||||
return 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:
|
||||
logger.info('Could not take out TTL lock')
|
||||
return ret
|
||||
|
||||
def set_failover_value(self, 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:
|
||||
self._client.retry(self._client.set, self.failover_path, 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
|
||||
except NoNodeError:
|
||||
return value == '' or (index is None and self._create(self.failover_path, value))
|
||||
except:
|
||||
logging.exception('set_failover_value')
|
||||
return False
|
||||
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:
|
||||
logger.exception('Failed to update %s', key)
|
||||
return False
|
||||
|
||||
def set_failover_value(self, value, index=None):
|
||||
return self._set_or_create(self.failover_path, value, index)
|
||||
|
||||
def set_config_value(self, value, index=None):
|
||||
try:
|
||||
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
|
||||
return self._set_or_create(self.config_path, value, index, retry=True)
|
||||
|
||||
def initialize(self, create_new=True, sysid=""):
|
||||
return self._create(self.initialize_path, sysid, makepath=True) if create_new \
|
||||
else self._client.retry(self._client.set, self.initialize_path, sysid.encode("utf-8"))
|
||||
sysid = 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, permanent=False):
|
||||
cluster = self.cluster
|
||||
member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
|
||||
data = data.encode('utf-8')
|
||||
if member and self._client.client_id is not None and member.session != self._client.client_id[0]:
|
||||
encoded_data = json.dumps(data, separators=(',', ':')).encode('utf-8')
|
||||
if member and (self._client.client_id is not None and member.session != self._client.client_id[0] or
|
||||
not (deep_compare(member.data.get('tags', {}), data.get('tags', {})) and
|
||||
member.data.get('version') == data.get('version') and
|
||||
member.data.get('checkpoint_after_promote') == data.get('checkpoint_after_promote'))):
|
||||
try:
|
||||
self._client.delete_async(self.member_path).get(timeout=1)
|
||||
except NoNodeError:
|
||||
pass
|
||||
except:
|
||||
except Exception:
|
||||
return False
|
||||
member = None
|
||||
|
||||
if member:
|
||||
if data == self._my_member_data:
|
||||
if deep_compare(data, member.data):
|
||||
return True
|
||||
else:
|
||||
try:
|
||||
self._client.create_async(self.member_path, data, makepath=True, ephemeral=not permanent).get(timeout=1)
|
||||
self._my_member_data = data
|
||||
self._client.create_async(self.member_path, encoded_data, makepath=True,
|
||||
ephemeral=not permanent).get(timeout=1)
|
||||
return True
|
||||
except Exception as e:
|
||||
if not isinstance(e, NodeExistsError):
|
||||
logger.exception('touch_member')
|
||||
return False
|
||||
try:
|
||||
self._client.set_async(self.member_path, data).get(timeout=1)
|
||||
self._my_member_data = data
|
||||
self._client.set_async(self.member_path, encoded_data).get(timeout=1)
|
||||
return True
|
||||
except:
|
||||
except Exception:
|
||||
logger.exception('touch_member')
|
||||
|
||||
return False
|
||||
@@ -274,26 +313,13 @@ class ZooKeeper(AbstractDCS):
|
||||
return self.attempt_to_acquire_leader()
|
||||
|
||||
def _write_leader_optime(self, last_operation):
|
||||
last_operation = last_operation.encode('utf-8')
|
||||
try:
|
||||
self._client.set_async(self.leader_optime_path, last_operation).get(timeout=1)
|
||||
return True
|
||||
except NoNodeError:
|
||||
try:
|
||||
self._client.create_async(self.leader_optime_path, last_operation, makepath=True).get(timeout=1)
|
||||
return True
|
||||
except:
|
||||
logger.exception('Failed to create %s', self.leader_optime_path)
|
||||
except:
|
||||
logger.exception('Failed to update %s', self.leader_optime_path)
|
||||
return False
|
||||
return self._set_or_create(self.leader_optime_path, last_operation)
|
||||
|
||||
def update_leader(self):
|
||||
def _update_leader(self):
|
||||
return True
|
||||
|
||||
def delete_leader(self):
|
||||
def _delete_leader(self):
|
||||
self._client.restart()
|
||||
self._my_member_data = None
|
||||
return True
|
||||
|
||||
def _cancel_initialization(self):
|
||||
@@ -304,7 +330,7 @@ class ZooKeeper(AbstractDCS):
|
||||
def cancel_initialization(self):
|
||||
try:
|
||||
self._client.retry(self._cancel_initialization)
|
||||
except:
|
||||
except Exception:
|
||||
logger.exception("Unable to delete initialize key")
|
||||
|
||||
def delete_cluster(self):
|
||||
@@ -313,15 +339,11 @@ class ZooKeeper(AbstractDCS):
|
||||
except NoNodeError:
|
||||
return True
|
||||
|
||||
def set_history_value(self, value):
|
||||
return self._set_or_create(self.history_path, value)
|
||||
|
||||
def set_sync_state_value(self, value, index=None):
|
||||
try:
|
||||
self._client.retry(self._client.set, self.sync_path, value.encode('utf-8'), version=index or -1)
|
||||
return True
|
||||
except NoNodeError:
|
||||
return value == '' or (index is None and self._create(self.sync_path, value))
|
||||
except:
|
||||
logging.exception('set_sync_state_value')
|
||||
return False
|
||||
return self._set_or_create(self.sync_path, value, index, retry=True, do_not_create_empty=True)
|
||||
|
||||
def delete_sync_state(self, index=None):
|
||||
return self.set_sync_state_value("{}", index)
|
||||
|
||||
@@ -23,3 +23,11 @@ class DCSError(PatroniException):
|
||||
|
||||
class PostgresConnectionException(PostgresException):
|
||||
pass
|
||||
|
||||
|
||||
class WatchdogError(PatroniException):
|
||||
pass
|
||||
|
||||
|
||||
class ConfigParseError(PatroniException):
|
||||
pass
|
||||
|
||||
+668
-185
File diff suppressed because it is too large
Load Diff
+194
@@ -0,0 +1,194 @@
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
from copy import deepcopy
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from patroni.utils import deep_compare
|
||||
from six.moves.queue import Queue, Full
|
||||
from threading import Lock, Thread
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def debug_exception(logger_obj, msg, *args, **kwargs):
|
||||
kwargs.pop("exc_info", False)
|
||||
if logger_obj.isEnabledFor(logging.DEBUG):
|
||||
logger_obj.debug(msg, *args, exc_info=True, **kwargs)
|
||||
else:
|
||||
msg = "{0}, DETAIL: '{1}'".format(msg, sys.exc_info()[1])
|
||||
logger_obj.error(msg, *args, exc_info=False, **kwargs)
|
||||
|
||||
|
||||
def error_exception(logger_obj, msg, *args, **kwargs):
|
||||
exc_info = kwargs.pop("exc_info", True)
|
||||
logger_obj.error(msg, *args, exc_info=exc_info, **kwargs)
|
||||
|
||||
|
||||
class QueueHandler(logging.Handler):
|
||||
|
||||
def __init__(self):
|
||||
logging.Handler.__init__(self)
|
||||
self.queue = Queue()
|
||||
self._records_lost = 0
|
||||
|
||||
def _put_record(self, record):
|
||||
self.format(record)
|
||||
record.msg = record.message
|
||||
record.args = None
|
||||
record.exc_info = None
|
||||
self.queue.put_nowait(record)
|
||||
|
||||
def _try_to_report_lost_records(self):
|
||||
if self._records_lost:
|
||||
try:
|
||||
record = _LOGGER.makeRecord(_LOGGER.name, logging.WARNING, __file__, 0,
|
||||
'QueueHandler has lost %s log records',
|
||||
(self._records_lost,), None, 'emit')
|
||||
self._put_record(record)
|
||||
self._records_lost = 0
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def emit(self, record):
|
||||
try:
|
||||
self._put_record(record)
|
||||
self._try_to_report_lost_records()
|
||||
except Exception:
|
||||
self._records_lost += 1
|
||||
|
||||
@property
|
||||
def records_lost(self):
|
||||
return self._records_lost
|
||||
|
||||
|
||||
class ProxyHandler(logging.Handler):
|
||||
|
||||
def __init__(self, patroni_logger):
|
||||
logging.Handler.__init__(self)
|
||||
self.patroni_logger = patroni_logger
|
||||
|
||||
def emit(self, record):
|
||||
self.patroni_logger.log_handler.handle(record)
|
||||
|
||||
|
||||
class PatroniLogger(Thread):
|
||||
|
||||
DEFAULT_LEVEL = 'INFO'
|
||||
DEFAULT_TRACEBACK_LEVEL = 'ERROR'
|
||||
DEFAULT_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
|
||||
|
||||
NORMAL_LOG_QUEUE_SIZE = 2 # When everything goes normal Patroni writes only 2 messages per HA loop
|
||||
DEFAULT_MAX_QUEUE_SIZE = 1000
|
||||
LOGGING_BROKEN_EXIT_CODE = 5
|
||||
|
||||
def __init__(self):
|
||||
super(PatroniLogger, self).__init__()
|
||||
self._queue_handler = QueueHandler()
|
||||
self._root_logger = logging.getLogger()
|
||||
self._config = None
|
||||
self.log_handler = None
|
||||
self.log_handler_lock = Lock()
|
||||
self._old_handlers = []
|
||||
self.reload_config({'level': 'DEBUG'})
|
||||
# We will switch to the QueueHandler only when thread was started.
|
||||
# This is necessary to protect from the cases when Patroni constructor
|
||||
# failed and PatroniLogger thread remain running and prevent shutdown.
|
||||
self._proxy_handler = ProxyHandler(self)
|
||||
self._root_logger.addHandler(self._proxy_handler)
|
||||
|
||||
def update_loggers(self):
|
||||
loggers = deepcopy(self._config.get('loggers') or {})
|
||||
for name, logger in self._root_logger.manager.loggerDict.items():
|
||||
if not isinstance(logger, logging.PlaceHolder):
|
||||
level = loggers.pop(name, logging.NOTSET)
|
||||
logger.setLevel(level)
|
||||
|
||||
for name, level in loggers.items():
|
||||
logger = self._root_logger.manager.getLogger(name)
|
||||
logger.setLevel(level)
|
||||
|
||||
def reload_config(self, config):
|
||||
if self._config is None or not deep_compare(self._config, config):
|
||||
with self._queue_handler.queue.mutex:
|
||||
self._queue_handler.queue.maxsize = config.get('max_queue_size', self.DEFAULT_MAX_QUEUE_SIZE)
|
||||
|
||||
self._root_logger.setLevel(config.get('level', PatroniLogger.DEFAULT_LEVEL))
|
||||
if config.get('traceback_level', PatroniLogger.DEFAULT_TRACEBACK_LEVEL).lower() == 'debug':
|
||||
logging.Logger.exception = debug_exception
|
||||
else:
|
||||
logging.Logger.exception = error_exception
|
||||
|
||||
new_handler = None
|
||||
if 'dir' in config:
|
||||
if not isinstance(self.log_handler, RotatingFileHandler):
|
||||
new_handler = RotatingFileHandler(os.path.join(config['dir'], __name__))
|
||||
handler = new_handler or self.log_handler
|
||||
handler.maxBytes = int(config.get('file_size', 25000000))
|
||||
handler.backupCount = int(config.get('file_num', 4))
|
||||
else:
|
||||
if self.log_handler is None or isinstance(self.log_handler, RotatingFileHandler):
|
||||
new_handler = logging.StreamHandler()
|
||||
handler = new_handler or self.log_handler
|
||||
|
||||
oldlogformat = (self._config or {}).get('format', PatroniLogger.DEFAULT_FORMAT)
|
||||
logformat = config.get('format', PatroniLogger.DEFAULT_FORMAT)
|
||||
|
||||
olddateformat = (self._config or {}).get('dateformat') or None
|
||||
dateformat = config.get('dateformat') or None # Convert empty string to `None`
|
||||
|
||||
if oldlogformat != logformat or olddateformat != dateformat or new_handler:
|
||||
handler.setFormatter(logging.Formatter(logformat, dateformat))
|
||||
|
||||
if new_handler:
|
||||
with self.log_handler_lock:
|
||||
if self.log_handler:
|
||||
self._old_handlers.append(self.log_handler)
|
||||
self.log_handler = new_handler
|
||||
|
||||
self._config = config.copy()
|
||||
self.update_loggers()
|
||||
|
||||
def _close_old_handlers(self):
|
||||
while True:
|
||||
with self.log_handler_lock:
|
||||
if not self._old_handlers:
|
||||
break
|
||||
handler = self._old_handlers.pop()
|
||||
try:
|
||||
handler.close()
|
||||
except Exception:
|
||||
_LOGGER.exception('Failed to close the old log handler %s', handler)
|
||||
|
||||
def run(self):
|
||||
# switch to QueueHandler only when the thread was started
|
||||
with self.log_handler_lock:
|
||||
self._root_logger.addHandler(self._queue_handler)
|
||||
self._root_logger.removeHandler(self._proxy_handler)
|
||||
|
||||
while True:
|
||||
self._close_old_handlers()
|
||||
|
||||
record = self._queue_handler.queue.get(True)
|
||||
if record is None:
|
||||
break
|
||||
|
||||
self.log_handler.handle(record)
|
||||
self._queue_handler.queue.task_done()
|
||||
|
||||
def shutdown(self):
|
||||
try:
|
||||
self._queue_handler.queue.put_nowait(None)
|
||||
except Full: # Queue is full.
|
||||
# It seems that logging is not working, exiting with non-standard exit-code is the best we can do.
|
||||
sys.exit(self.LOGGING_BROKEN_EXIT_CODE)
|
||||
self.join()
|
||||
logging.shutdown()
|
||||
|
||||
@property
|
||||
def queue_size(self):
|
||||
return self._queue_handler.queue.qsize()
|
||||
|
||||
@property
|
||||
def records_lost(self):
|
||||
return self._queue_handler.records_lost
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,937 @@
|
||||
import logging
|
||||
import os
|
||||
import psycopg2
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from contextlib import contextmanager
|
||||
from copy import deepcopy
|
||||
from dateutil import tz
|
||||
from datetime import datetime
|
||||
from patroni.postgresql.callback_executor import CallbackExecutor
|
||||
from patroni.postgresql.bootstrap import Bootstrap
|
||||
from patroni.postgresql.cancellable import CancellableSubprocess
|
||||
from patroni.postgresql.config import ConfigHandler, mtime
|
||||
from patroni.postgresql.connection import Connection, get_connection_cursor
|
||||
from patroni.postgresql.misc import parse_history, parse_lsn, postgres_major_version_to_int
|
||||
from patroni.postgresql.postmaster import PostmasterProcess
|
||||
from patroni.postgresql.slots import SlotsHandler
|
||||
from patroni.exceptions import PostgresConnectionException
|
||||
from patroni.utils import Retry, RetryFailedError, polling_loop, data_directory_is_empty, parse_int
|
||||
from threading import current_thread, Lock
|
||||
from psutil import TimeoutExpired
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ACTION_ON_START = "on_start"
|
||||
ACTION_ON_STOP = "on_stop"
|
||||
ACTION_ON_RESTART = "on_restart"
|
||||
ACTION_ON_RELOAD = "on_reload"
|
||||
ACTION_ON_ROLE_CHANGE = "on_role_change"
|
||||
ACTION_NOOP = "noop"
|
||||
|
||||
STATE_RUNNING = 'running'
|
||||
STATE_REJECT = 'rejecting connections'
|
||||
STATE_NO_RESPONSE = 'not responding'
|
||||
STATE_UNKNOWN = 'unknown'
|
||||
|
||||
STOP_POLLING_INTERVAL = 1
|
||||
|
||||
|
||||
@contextmanager
|
||||
def null_context():
|
||||
yield
|
||||
|
||||
|
||||
class Postgresql(object):
|
||||
|
||||
POSTMASTER_START_TIME = "pg_catalog.to_char(pg_catalog.pg_postmaster_start_time(), 'YYYY-MM-DD HH24:MI:SS.MS TZ')"
|
||||
TL_LSN = ("CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0 "
|
||||
"ELSE ('x' || pg_catalog.substr(pg_catalog.pg_{0}file_name("
|
||||
"pg_catalog.pg_current_{0}_{1}()), 1, 8))::bit(32)::int END, " # master timeline
|
||||
"CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0 "
|
||||
"ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), '0/0')::bigint END, " # write_lsn
|
||||
"pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_last_{0}_replay_{1}(), '0/0')::bigint, "
|
||||
"pg_catalog.pg_{0}_{1}_diff(COALESCE(pg_catalog.pg_last_{0}_receive_{1}(), '0/0'), '0/0')::bigint, "
|
||||
"pg_catalog.pg_is_in_recovery() AND pg_catalog.pg_is_{0}_replay_paused()")
|
||||
|
||||
def __init__(self, config):
|
||||
self.name = config['name']
|
||||
self.scope = config['scope']
|
||||
self._data_dir = config['data_dir']
|
||||
self._database = config.get('database', 'postgres')
|
||||
self._version_file = os.path.join(self._data_dir, 'PG_VERSION')
|
||||
self._pg_control = os.path.join(self._data_dir, 'global', 'pg_control')
|
||||
self._major_version = self.get_major_version()
|
||||
|
||||
self._state_lock = Lock()
|
||||
self.set_state('stopped')
|
||||
|
||||
self._pending_restart = False
|
||||
self._connection = Connection()
|
||||
self.config = ConfigHandler(self, config)
|
||||
self.config.check_directories()
|
||||
|
||||
self._bin_dir = config.get('bin_dir') or ''
|
||||
self.bootstrap = Bootstrap(self)
|
||||
self.bootstrapping = False
|
||||
self.__thread_ident = current_thread().ident
|
||||
|
||||
self.slots_handler = SlotsHandler(self)
|
||||
|
||||
self._callback_executor = CallbackExecutor()
|
||||
self.__cb_called = False
|
||||
self.__cb_pending = None
|
||||
|
||||
self.cancellable = CancellableSubprocess()
|
||||
|
||||
self._sysid = None
|
||||
self.retry = Retry(max_tries=-1, deadline=config['retry_timeout']/2.0, max_delay=1,
|
||||
retry_exceptions=PostgresConnectionException)
|
||||
|
||||
# Retry 'pg_is_in_recovery()' only once
|
||||
self._is_leader_retry = Retry(max_tries=1, deadline=config['retry_timeout']/2.0, max_delay=1,
|
||||
retry_exceptions=PostgresConnectionException)
|
||||
|
||||
self._role_lock = Lock()
|
||||
self.set_role(self.get_postgres_role_from_data_directory())
|
||||
self._state_entry_timestamp = None
|
||||
|
||||
self._cluster_info_state = {}
|
||||
self._cached_replica_timeline = None
|
||||
|
||||
# Last known running process
|
||||
self._postmaster_proc = None
|
||||
|
||||
if self.is_running():
|
||||
self.set_state('running')
|
||||
self.set_role('master' if self.is_leader() else 'replica')
|
||||
self.config.write_postgresql_conf() # we are "joining" already running postgres
|
||||
hba_saved = self.config.replace_pg_hba()
|
||||
ident_saved = self.config.replace_pg_ident()
|
||||
if hba_saved or ident_saved:
|
||||
self.reload()
|
||||
elif self.role == 'master':
|
||||
self.set_role('demoted')
|
||||
|
||||
@property
|
||||
def create_replica_methods(self):
|
||||
return self.config.get('create_replica_methods', []) or self.config.get('create_replica_method', [])
|
||||
|
||||
@property
|
||||
def major_version(self):
|
||||
return self._major_version
|
||||
|
||||
@property
|
||||
def database(self):
|
||||
return self._database
|
||||
|
||||
@property
|
||||
def data_dir(self):
|
||||
return self._data_dir
|
||||
|
||||
@property
|
||||
def callback(self):
|
||||
return self.config.get('callbacks') or {}
|
||||
|
||||
@property
|
||||
def wal_dir(self):
|
||||
return os.path.join(self._data_dir, 'pg_' + self.wal_name)
|
||||
|
||||
@property
|
||||
def wal_name(self):
|
||||
return 'wal' if self._major_version >= 100000 else 'xlog'
|
||||
|
||||
@property
|
||||
def lsn_name(self):
|
||||
return 'lsn' if self._major_version >= 100000 else 'location'
|
||||
|
||||
@property
|
||||
def cluster_info_query(self):
|
||||
if self._major_version >= 90600:
|
||||
extra = (", CASE WHEN latest_end_lsn IS NULL THEN NULL ELSE received_tli END,"
|
||||
" slot_name, conninfo FROM pg_catalog.pg_stat_get_wal_receiver()")
|
||||
if self.role == 'standby_leader':
|
||||
extra = "timeline_id" + extra + ", pg_catalog.pg_control_checkpoint()"
|
||||
else:
|
||||
extra = "0" + extra
|
||||
else:
|
||||
extra = "0, NULL, NULL, NULL"
|
||||
|
||||
return ("SELECT " + self.TL_LSN + ", {2}").format(self.wal_name, self.lsn_name, extra)
|
||||
|
||||
def _version_file_exists(self):
|
||||
return not self.data_directory_empty() and os.path.isfile(self._version_file)
|
||||
|
||||
def get_major_version(self):
|
||||
if self._version_file_exists():
|
||||
try:
|
||||
with open(self._version_file) as f:
|
||||
return postgres_major_version_to_int(f.read().strip())
|
||||
except Exception:
|
||||
logger.exception('Failed to read PG_VERSION from %s', self._data_dir)
|
||||
return 0
|
||||
|
||||
def pgcommand(self, cmd):
|
||||
"""Returns path to the specified PostgreSQL command"""
|
||||
return os.path.join(self._bin_dir, cmd)
|
||||
|
||||
def pg_ctl(self, cmd, *args, **kwargs):
|
||||
"""Builds and executes pg_ctl command
|
||||
|
||||
:returns: `!True` when return_code == 0, otherwise `!False`"""
|
||||
|
||||
pg_ctl = [self.pgcommand('pg_ctl'), cmd]
|
||||
return subprocess.call(pg_ctl + ['-D', self._data_dir] + list(args), **kwargs) == 0
|
||||
|
||||
def pg_isready(self):
|
||||
"""Runs pg_isready to see if PostgreSQL is accepting connections.
|
||||
|
||||
:returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up."""
|
||||
|
||||
r = self.config.local_connect_kwargs
|
||||
cmd = [self.pgcommand('pg_isready'), '-p', r['port'], '-d', self._database]
|
||||
|
||||
# Host is not set if we are connecting via default unix socket
|
||||
if 'host' in r:
|
||||
cmd.extend(['-h', r['host']])
|
||||
|
||||
# We only need the username because pg_isready does not try to authenticate
|
||||
if 'user' in r:
|
||||
cmd.extend(['-U', r['user']])
|
||||
|
||||
ret = subprocess.call(cmd)
|
||||
return_codes = {0: STATE_RUNNING,
|
||||
1: STATE_REJECT,
|
||||
2: STATE_NO_RESPONSE,
|
||||
3: STATE_UNKNOWN}
|
||||
return return_codes.get(ret, STATE_UNKNOWN)
|
||||
|
||||
def reload_config(self, config, sighup=False):
|
||||
self.config.reload_config(config, sighup)
|
||||
self._is_leader_retry.deadline = self.retry.deadline = config['retry_timeout']/2.0
|
||||
|
||||
@property
|
||||
def pending_restart(self):
|
||||
return self._pending_restart
|
||||
|
||||
def set_pending_restart(self, value):
|
||||
self._pending_restart = value
|
||||
|
||||
@property
|
||||
def sysid(self):
|
||||
if not self._sysid and not self.bootstrapping:
|
||||
data = self.controldata()
|
||||
self._sysid = data.get('Database system identifier', "")
|
||||
return self._sysid
|
||||
|
||||
def get_postgres_role_from_data_directory(self):
|
||||
if self.data_directory_empty() or not self.controldata():
|
||||
return 'uninitialized'
|
||||
elif self.config.recovery_conf_exists():
|
||||
return 'replica'
|
||||
else:
|
||||
return 'master'
|
||||
|
||||
@property
|
||||
def server_version(self):
|
||||
return self._connection.server_version
|
||||
|
||||
def connection(self):
|
||||
return self._connection.get()
|
||||
|
||||
def set_connection_kwargs(self, kwargs):
|
||||
self._connection.set_conn_kwargs(kwargs)
|
||||
|
||||
def _query(self, sql, *params):
|
||||
"""We are always using the same cursor, therefore this method is not thread-safe!!!
|
||||
You can call it from different threads only if you are holding explicit `AsyncExecutor` lock,
|
||||
because the main thread is always holding this lock when running HA cycle."""
|
||||
cursor = None
|
||||
try:
|
||||
cursor = self._connection.cursor()
|
||||
cursor.execute(sql, params)
|
||||
return cursor
|
||||
except psycopg2.Error as e:
|
||||
if cursor and cursor.connection.closed == 0:
|
||||
# When connected via unix socket, psycopg2 can't recoginze 'connection lost'
|
||||
# and leaves `_cursor_holder.connection.closed == 0`, but psycopg2.OperationalError
|
||||
# is still raised (what is correct). It doesn't make sense to continiue with existing
|
||||
# connection and we will close it, to avoid its reuse by the `cursor` method.
|
||||
if isinstance(e, psycopg2.OperationalError):
|
||||
self._connection.close()
|
||||
else:
|
||||
raise e
|
||||
if self.state == 'restarting':
|
||||
raise RetryFailedError('cluster is being restarted')
|
||||
raise PostgresConnectionException('connection problems')
|
||||
|
||||
def query(self, sql, *args, **kwargs):
|
||||
if not kwargs.get('retry', True):
|
||||
return self._query(sql, *args)
|
||||
try:
|
||||
return self.retry(self._query, sql, *args)
|
||||
except RetryFailedError as e:
|
||||
raise PostgresConnectionException(str(e))
|
||||
|
||||
def pg_control_exists(self):
|
||||
return os.path.isfile(self._pg_control)
|
||||
|
||||
def data_directory_empty(self):
|
||||
if self.pg_control_exists():
|
||||
return False
|
||||
return data_directory_is_empty(self._data_dir)
|
||||
|
||||
def replica_method_options(self, method):
|
||||
return deepcopy(self.config.get(method, {}))
|
||||
|
||||
def replica_method_can_work_without_replication_connection(self, method):
|
||||
return method != 'basebackup' and self.replica_method_options(method).get('no_master')
|
||||
|
||||
def can_create_replica_without_replication_connection(self, replica_methods=None):
|
||||
""" go through the replication methods to see if there are ones
|
||||
that does not require a working replication connection.
|
||||
"""
|
||||
if replica_methods is None:
|
||||
replica_methods = self.create_replica_methods
|
||||
return any(self.replica_method_can_work_without_replication_connection(m) for m in replica_methods)
|
||||
|
||||
def reset_cluster_info_state(self):
|
||||
self._cluster_info_state = {}
|
||||
|
||||
def _cluster_info_state_get(self, name):
|
||||
if not self._cluster_info_state:
|
||||
try:
|
||||
result = self._is_leader_retry(self._query, self.cluster_info_query).fetchone()
|
||||
self._cluster_info_state = dict(zip(['timeline', 'wal_position', 'replayed_location',
|
||||
'received_location', 'replay_paused', 'pg_control_timeline',
|
||||
'received_tli', 'slot_name', 'conninfo'], result))
|
||||
except RetryFailedError as e: # SELECT failed two times
|
||||
self._cluster_info_state = {'error': str(e)}
|
||||
if not self.is_starting() and self.pg_isready() == STATE_REJECT:
|
||||
self.set_state('starting')
|
||||
|
||||
if 'error' in self._cluster_info_state:
|
||||
raise PostgresConnectionException(self._cluster_info_state['error'])
|
||||
|
||||
return self._cluster_info_state.get(name)
|
||||
|
||||
def replayed_location(self):
|
||||
return self._cluster_info_state_get('replayed_location')
|
||||
|
||||
def received_location(self):
|
||||
return self._cluster_info_state_get('received_location')
|
||||
|
||||
def primary_slot_name(self):
|
||||
return self._cluster_info_state_get('slot_name')
|
||||
|
||||
def primary_conninfo(self):
|
||||
return self._cluster_info_state_get('conninfo')
|
||||
|
||||
def received_timeline(self):
|
||||
return self._cluster_info_state_get('received_tli')
|
||||
|
||||
def is_leader(self):
|
||||
return bool(self._cluster_info_state_get('timeline'))
|
||||
|
||||
def pg_control_timeline(self):
|
||||
try:
|
||||
return int(self.controldata().get("Latest checkpoint's TimeLineID"))
|
||||
except (TypeError, ValueError):
|
||||
logger.exception('Failed to parse timeline from pg_controldata output')
|
||||
|
||||
def latest_checkpoint_location(self):
|
||||
"""Returns checkpoint location for the cleanly shut down primary"""
|
||||
|
||||
data = self.controldata()
|
||||
lsn = data.get('Latest checkpoint location')
|
||||
if data.get('Database cluster state') == 'shut down' and lsn:
|
||||
try:
|
||||
return str(parse_lsn(lsn))
|
||||
except (IndexError, ValueError) as e:
|
||||
logger.error('Exception when parsing lsn %s: %r', lsn, e)
|
||||
|
||||
def is_running(self):
|
||||
"""Returns PostmasterProcess if one is running on the data directory or None. If most recently seen process
|
||||
is running updates the cached process based on pid file."""
|
||||
if self._postmaster_proc:
|
||||
if self._postmaster_proc.is_running():
|
||||
return self._postmaster_proc
|
||||
self._postmaster_proc = None
|
||||
|
||||
# we noticed that postgres was restarted, force syncing of replication
|
||||
self.slots_handler.schedule()
|
||||
|
||||
self._postmaster_proc = PostmasterProcess.from_pidfile(self._data_dir)
|
||||
return self._postmaster_proc
|
||||
|
||||
@property
|
||||
def cb_called(self):
|
||||
return self.__cb_called
|
||||
|
||||
def call_nowait(self, cb_name):
|
||||
""" pick a callback command and call it without waiting for it to finish """
|
||||
if self.bootstrapping:
|
||||
return
|
||||
if cb_name in (ACTION_ON_START, ACTION_ON_STOP, ACTION_ON_RESTART, ACTION_ON_ROLE_CHANGE):
|
||||
self.__cb_called = True
|
||||
|
||||
if self.callback and cb_name in self.callback:
|
||||
cmd = self.callback[cb_name]
|
||||
try:
|
||||
cmd = shlex.split(self.callback[cb_name]) + [cb_name, self.role, self.scope]
|
||||
self._callback_executor.call(cmd)
|
||||
except Exception:
|
||||
logger.exception('callback %s %s %s %s failed', cmd, cb_name, self.role, self.scope)
|
||||
|
||||
@property
|
||||
def role(self):
|
||||
with self._role_lock:
|
||||
return self._role
|
||||
|
||||
def set_role(self, value):
|
||||
with self._role_lock:
|
||||
self._role = value
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
with self._state_lock:
|
||||
return self._state
|
||||
|
||||
def set_state(self, value):
|
||||
with self._state_lock:
|
||||
self._state = value
|
||||
self._state_entry_timestamp = time.time()
|
||||
|
||||
def time_in_state(self):
|
||||
return time.time() - self._state_entry_timestamp
|
||||
|
||||
def is_starting(self):
|
||||
return self.state == 'starting'
|
||||
|
||||
def wait_for_port_open(self, postmaster, timeout):
|
||||
"""Waits until PostgreSQL opens ports."""
|
||||
for _ in polling_loop(timeout):
|
||||
if self.cancellable.is_cancelled:
|
||||
return False
|
||||
|
||||
if not postmaster.is_running():
|
||||
logger.error('postmaster is not running')
|
||||
self.set_state('start failed')
|
||||
return False
|
||||
|
||||
isready = self.pg_isready()
|
||||
if isready != STATE_NO_RESPONSE:
|
||||
if isready not in [STATE_REJECT, STATE_RUNNING]:
|
||||
logger.warning("Can't determine PostgreSQL startup status, assuming running")
|
||||
return True
|
||||
|
||||
logger.warning("Timed out waiting for PostgreSQL to start")
|
||||
return False
|
||||
|
||||
def start(self, timeout=None, task=None, block_callbacks=False, role=None):
|
||||
"""Start PostgreSQL
|
||||
|
||||
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
|
||||
or failure.
|
||||
|
||||
:returns: True if start was initiated and postmaster ports are open, False if start failed"""
|
||||
# make sure we close all connections established against
|
||||
# the former node, otherwise, we might get a stalled one
|
||||
# after kill -9, which would report incorrect data to
|
||||
# patroni.
|
||||
self._connection.close()
|
||||
|
||||
if self.is_running():
|
||||
logger.error('Cannot start PostgreSQL because one is already running.')
|
||||
self.set_state('starting')
|
||||
return True
|
||||
|
||||
if not block_callbacks:
|
||||
self.__cb_pending = ACTION_ON_START
|
||||
|
||||
self.set_role(role or self.get_postgres_role_from_data_directory())
|
||||
|
||||
self.set_state('starting')
|
||||
self._pending_restart = False
|
||||
|
||||
try:
|
||||
configuration = self.config.effective_configuration
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
self.config.check_directories()
|
||||
self.config.write_postgresql_conf(configuration)
|
||||
self.config.resolve_connection_addresses()
|
||||
self.config.replace_pg_hba()
|
||||
self.config.replace_pg_ident()
|
||||
|
||||
options = ['--{0}={1}'.format(p, configuration[p]) for p in self.config.CMDLINE_OPTIONS
|
||||
if p in configuration and p != 'wal_keep_segments']
|
||||
|
||||
if self.cancellable.is_cancelled:
|
||||
return False
|
||||
|
||||
with task or null_context():
|
||||
if task and task.is_cancelled:
|
||||
logger.info("PostgreSQL start cancelled.")
|
||||
return False
|
||||
|
||||
self._postmaster_proc = PostmasterProcess.start(self.pgcommand('postgres'),
|
||||
self._data_dir,
|
||||
self.config.postgresql_conf,
|
||||
options)
|
||||
|
||||
if task:
|
||||
task.complete(self._postmaster_proc)
|
||||
|
||||
start_timeout = timeout
|
||||
if not start_timeout:
|
||||
try:
|
||||
start_timeout = float(self.config.get('pg_ctl_timeout', 60))
|
||||
except ValueError:
|
||||
start_timeout = 60
|
||||
|
||||
# We want postmaster to open ports before we continue
|
||||
if not self._postmaster_proc or not self.wait_for_port_open(self._postmaster_proc, start_timeout):
|
||||
return False
|
||||
|
||||
ret = self.wait_for_startup(start_timeout)
|
||||
if ret is not None:
|
||||
return ret
|
||||
elif timeout is not None:
|
||||
return False
|
||||
else:
|
||||
return None
|
||||
|
||||
def checkpoint(self, connect_kwargs=None, timeout=None):
|
||||
check_not_is_in_recovery = connect_kwargs is not None
|
||||
connect_kwargs = connect_kwargs or self.config.local_connect_kwargs
|
||||
for p in ['connect_timeout', 'options']:
|
||||
connect_kwargs.pop(p, None)
|
||||
if timeout:
|
||||
connect_kwargs['connect_timeout'] = timeout
|
||||
try:
|
||||
with get_connection_cursor(**connect_kwargs) as cur:
|
||||
cur.execute("SET statement_timeout = 0")
|
||||
if check_not_is_in_recovery:
|
||||
cur.execute('SELECT pg_catalog.pg_is_in_recovery()')
|
||||
if cur.fetchone()[0]:
|
||||
return 'is_in_recovery=true'
|
||||
return cur.execute('CHECKPOINT')
|
||||
except psycopg2.Error:
|
||||
logger.exception('Exception during CHECKPOINT')
|
||||
return 'not accessible or not healty'
|
||||
|
||||
def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None, stop_timeout=None):
|
||||
"""Stop PostgreSQL
|
||||
|
||||
Supports a callback when a safepoint is reached. A safepoint is when no user backend can return a successful
|
||||
commit to users. Currently this means we wait for user backends to close. But in the future alternate mechanisms
|
||||
could be added.
|
||||
|
||||
:param on_safepoint: This callback is called when no user backends are running.
|
||||
"""
|
||||
if checkpoint is None:
|
||||
checkpoint = False if mode == 'immediate' else True
|
||||
|
||||
success, pg_signaled = self._do_stop(mode, block_callbacks, checkpoint, on_safepoint, stop_timeout)
|
||||
if success:
|
||||
# block_callbacks is used during restart to avoid
|
||||
# running start/stop callbacks in addition to restart ones
|
||||
if not block_callbacks:
|
||||
self.set_state('stopped')
|
||||
if pg_signaled:
|
||||
self.call_nowait(ACTION_ON_STOP)
|
||||
else:
|
||||
logger.warning('pg_ctl stop failed')
|
||||
self.set_state('stop failed')
|
||||
return success
|
||||
|
||||
def _do_stop(self, mode, block_callbacks, checkpoint, on_safepoint, stop_timeout):
|
||||
postmaster = self.is_running()
|
||||
if not postmaster:
|
||||
if on_safepoint:
|
||||
on_safepoint()
|
||||
return True, False
|
||||
|
||||
if checkpoint and not self.is_starting():
|
||||
self.checkpoint(timeout=stop_timeout)
|
||||
|
||||
if not block_callbacks:
|
||||
self.set_state('stopping')
|
||||
|
||||
# Send signal to postmaster to stop
|
||||
success = postmaster.signal_stop(mode, self.pgcommand('pg_ctl'))
|
||||
if success is not None:
|
||||
if success and on_safepoint:
|
||||
on_safepoint()
|
||||
return success, True
|
||||
|
||||
# We can skip safepoint detection if we don't have a callback
|
||||
if on_safepoint:
|
||||
# Wait for our connection to terminate so we can be sure that no new connections are being initiated
|
||||
self._wait_for_connection_close(postmaster)
|
||||
postmaster.wait_for_user_backends_to_close()
|
||||
on_safepoint()
|
||||
|
||||
try:
|
||||
postmaster.wait(timeout=stop_timeout)
|
||||
except TimeoutExpired:
|
||||
logger.warning("Timeout during postmaster stop, aborting Postgres.")
|
||||
if not self.terminate_postmaster(postmaster, mode, stop_timeout):
|
||||
postmaster.wait()
|
||||
|
||||
return True, True
|
||||
|
||||
def terminate_postmaster(self, postmaster, mode, stop_timeout):
|
||||
if mode in ['fast', 'smart']:
|
||||
try:
|
||||
success = postmaster.signal_stop('immediate', self.pgcommand('pg_ctl'))
|
||||
if success:
|
||||
return True
|
||||
postmaster.wait(timeout=stop_timeout)
|
||||
return True
|
||||
except TimeoutExpired:
|
||||
pass
|
||||
logger.warning("Sending SIGKILL to Postmaster and its children")
|
||||
return postmaster.signal_kill()
|
||||
|
||||
def terminate_starting_postmaster(self, postmaster):
|
||||
"""Terminates a postmaster that has not yet opened ports or possibly even written a pid file. Blocks
|
||||
until the process goes away."""
|
||||
postmaster.signal_stop('immediate', self.pgcommand('pg_ctl'))
|
||||
postmaster.wait()
|
||||
|
||||
def _wait_for_connection_close(self, postmaster):
|
||||
try:
|
||||
with self.connection().cursor() as cur:
|
||||
while postmaster.is_running(): # Need a timeout here?
|
||||
cur.execute("SELECT 1")
|
||||
time.sleep(STOP_POLLING_INTERVAL)
|
||||
except psycopg2.Error:
|
||||
pass
|
||||
|
||||
def reload(self, block_callbacks=False):
|
||||
ret = self.pg_ctl('reload')
|
||||
if ret and not block_callbacks:
|
||||
self.call_nowait(ACTION_ON_RELOAD)
|
||||
return ret
|
||||
|
||||
def check_for_startup(self):
|
||||
"""Checks PostgreSQL status and returns if PostgreSQL is in the middle of startup."""
|
||||
return self.is_starting() and not self.check_startup_state_changed()
|
||||
|
||||
def check_startup_state_changed(self):
|
||||
"""Checks if PostgreSQL has completed starting up or failed or still starting.
|
||||
|
||||
Should only be called when state == 'starting'
|
||||
|
||||
:returns: True if state was changed from 'starting'
|
||||
"""
|
||||
ready = self.pg_isready()
|
||||
|
||||
if ready == STATE_REJECT:
|
||||
return False
|
||||
elif ready == STATE_NO_RESPONSE:
|
||||
ret = not self.is_running()
|
||||
if ret:
|
||||
self.set_state('start failed')
|
||||
self.slots_handler.schedule(False) # TODO: can remove this?
|
||||
self.config.save_configuration_files(True) # TODO: maybe remove this?
|
||||
return ret
|
||||
else:
|
||||
if ready != STATE_RUNNING:
|
||||
# Bad configuration or unexpected OS error. No idea of PostgreSQL status.
|
||||
# Let the main loop of run cycle clean up the mess.
|
||||
logger.warning("%s status returned from pg_isready",
|
||||
"Unknown" if ready == STATE_UNKNOWN else "Invalid")
|
||||
self.set_state('running')
|
||||
self.slots_handler.schedule()
|
||||
self.config.save_configuration_files(True)
|
||||
# TODO: __cb_pending can be None here after PostgreSQL restarts on its own. Do we want to call the callback?
|
||||
# Previously we didn't even notice.
|
||||
action = self.__cb_pending or ACTION_ON_START
|
||||
self.call_nowait(action)
|
||||
self.__cb_pending = None
|
||||
|
||||
return True
|
||||
|
||||
def wait_for_startup(self, timeout=None):
|
||||
"""Waits for PostgreSQL startup to complete or fail.
|
||||
|
||||
:returns: True if start was successful, False otherwise"""
|
||||
if not self.is_starting():
|
||||
# Should not happen
|
||||
logger.warning("wait_for_startup() called when not in starting state")
|
||||
|
||||
while not self.check_startup_state_changed():
|
||||
if self.cancellable.is_cancelled or timeout and self.time_in_state() > timeout:
|
||||
return None
|
||||
time.sleep(1)
|
||||
|
||||
return self.state == 'running'
|
||||
|
||||
def restart(self, timeout=None, task=None, block_callbacks=False, role=None):
|
||||
"""Restarts PostgreSQL.
|
||||
|
||||
When timeout parameter is set the call will block either until PostgreSQL has started, failed to start or
|
||||
timeout arrives.
|
||||
|
||||
:returns: True when restart was successful and timeout did not expire when waiting.
|
||||
"""
|
||||
self.set_state('restarting')
|
||||
if not block_callbacks:
|
||||
self.__cb_pending = ACTION_ON_RESTART
|
||||
ret = self.stop(block_callbacks=True) and self.start(timeout, task, True, role)
|
||||
if not ret and not self.is_starting():
|
||||
self.set_state('restart failed ({0})'.format(self.state))
|
||||
return ret
|
||||
|
||||
def is_healthy(self):
|
||||
if not self.is_running():
|
||||
logger.warning('Postgresql is not running.')
|
||||
return False
|
||||
return True
|
||||
|
||||
def get_guc_value(self, name):
|
||||
cmd = [self.pgcommand('postgres'), self._data_dir, '-C', name]
|
||||
try:
|
||||
data = subprocess.check_output(cmd)
|
||||
if data:
|
||||
return data.decode('utf-8').strip()
|
||||
except Exception as e:
|
||||
logger.error('Failed to execute %s: %r', cmd, e)
|
||||
|
||||
def controldata(self):
|
||||
""" return the contents of pg_controldata, or non-True value if pg_controldata call failed """
|
||||
# Don't try to call pg_controldata during backup restore
|
||||
if self._version_file_exists() and self.state != 'creating replica':
|
||||
try:
|
||||
env = os.environ.copy()
|
||||
env.update(LANG='C', LC_ALL='C')
|
||||
data = subprocess.check_output([self.pgcommand('pg_controldata'), self._data_dir], env=env)
|
||||
if data:
|
||||
data = filter(lambda e: ':' in e, data.decode('utf-8').splitlines())
|
||||
# pg_controldata output depends on major version. Some of parameters are prefixed by 'Current '
|
||||
return {k.replace('Current ', '', 1): v.strip() for k, v in map(lambda e: e.split(':', 1), data)}
|
||||
except subprocess.CalledProcessError:
|
||||
logger.exception("Error when calling pg_controldata")
|
||||
return {}
|
||||
|
||||
@contextmanager
|
||||
def get_replication_connection_cursor(self, host='localhost', port=5432, **kwargs):
|
||||
conn_kwargs = self.config.replication.copy()
|
||||
conn_kwargs.update(host=host, port=int(port) if port else None, user=conn_kwargs.pop('username'),
|
||||
connect_timeout=3, replication=1, options='-c statement_timeout=2000')
|
||||
with get_connection_cursor(**conn_kwargs) as cur:
|
||||
yield cur
|
||||
|
||||
def get_replica_timeline(self):
|
||||
try:
|
||||
with self.get_replication_connection_cursor(**self.config.local_replication_address) as cur:
|
||||
cur.execute('IDENTIFY_SYSTEM')
|
||||
return cur.fetchone()[1]
|
||||
except Exception:
|
||||
logger.exception('Can not fetch local timeline and lsn from replication connection')
|
||||
|
||||
def replica_cached_timeline(self, master_timeline):
|
||||
if not self._cached_replica_timeline or not master_timeline or self._cached_replica_timeline != master_timeline:
|
||||
self._cached_replica_timeline = self.get_replica_timeline()
|
||||
return self._cached_replica_timeline
|
||||
|
||||
def get_master_timeline(self):
|
||||
return self._cluster_info_state_get('timeline')
|
||||
|
||||
def get_history(self, timeline):
|
||||
history_path = os.path.join(self.wal_dir, '{0:08X}.history'.format(timeline))
|
||||
history_mtime = mtime(history_path)
|
||||
if history_mtime:
|
||||
try:
|
||||
with open(history_path, 'r') as f:
|
||||
history = f.read()
|
||||
history = list(parse_history(history))
|
||||
if history[-1][0] == timeline - 1:
|
||||
history_mtime = datetime.fromtimestamp(history_mtime).replace(tzinfo=tz.tzlocal())
|
||||
history[-1].append(history_mtime.isoformat())
|
||||
return history
|
||||
except Exception:
|
||||
logger.exception('Failed to read and parse %s', (history_path,))
|
||||
|
||||
def follow(self, member, role='replica', timeout=None, do_reload=False):
|
||||
recovery_params = self.config.build_recovery_params(member)
|
||||
self.config.write_recovery_conf(recovery_params)
|
||||
|
||||
# When we demoting the master or standby_leader to replica or promoting replica to a standby_leader
|
||||
# and we know for sure that postgres was already running before, we will only execute on_role_change
|
||||
# callback and prevent execution of on_restart/on_start callback.
|
||||
# If the role remains the same (replica or standby_leader), we will execute on_start or on_restart
|
||||
change_role = self.cb_called and (self.role in ('master', 'demoted') or
|
||||
not {'standby_leader', 'replica'} - {self.role, role})
|
||||
if change_role:
|
||||
self.__cb_pending = ACTION_NOOP
|
||||
|
||||
if self.is_running():
|
||||
if do_reload:
|
||||
self.config.write_postgresql_conf()
|
||||
if self.reload(block_callbacks=change_role) and change_role:
|
||||
self.set_role(role)
|
||||
else:
|
||||
self.restart(block_callbacks=change_role, role=role)
|
||||
else:
|
||||
self.start(timeout=timeout, block_callbacks=change_role, role=role)
|
||||
|
||||
if change_role:
|
||||
# TODO: postpone this until start completes, or maybe do even earlier
|
||||
self.call_nowait(ACTION_ON_ROLE_CHANGE)
|
||||
return True
|
||||
|
||||
def _wait_promote(self, wait_seconds):
|
||||
for _ in polling_loop(wait_seconds):
|
||||
data = self.controldata()
|
||||
if data.get('Database cluster state') == 'in production':
|
||||
return True
|
||||
|
||||
def promote(self, wait_seconds, on_success=None, access_is_restricted=False):
|
||||
if self.role == 'master':
|
||||
return True
|
||||
ret = self.pg_ctl('promote', '-W')
|
||||
if ret:
|
||||
self.set_role('master')
|
||||
if on_success is not None:
|
||||
on_success()
|
||||
if not access_is_restricted:
|
||||
self.call_nowait(ACTION_ON_ROLE_CHANGE)
|
||||
ret = self._wait_promote(wait_seconds)
|
||||
return ret
|
||||
|
||||
@staticmethod
|
||||
def _wal_position(is_leader, wal_position, received_location, replayed_location):
|
||||
return wal_position if is_leader else max(received_location or 0, replayed_location or 0)
|
||||
|
||||
def timeline_wal_position(self):
|
||||
# This method could be called from different threads (simultaneously with some other `_query` calls).
|
||||
# If it is called not from main thread we will create a new cursor to execute statement.
|
||||
if current_thread().ident == self.__thread_ident:
|
||||
timeline = self._cluster_info_state_get('timeline')
|
||||
wal_position = self._cluster_info_state_get('wal_position')
|
||||
replayed_location = self.replayed_location()
|
||||
received_location = self.received_location()
|
||||
pg_control_timeline = self._cluster_info_state_get('pg_control_timeline')
|
||||
else:
|
||||
with self.connection().cursor() as cursor:
|
||||
cursor.execute(self.cluster_info_query)
|
||||
(timeline, wal_position, replayed_location,
|
||||
received_location, _, pg_control_timeline) = cursor.fetchone()[:6]
|
||||
|
||||
wal_position = self._wal_position(timeline, wal_position, received_location, replayed_location)
|
||||
return (timeline, wal_position, pg_control_timeline)
|
||||
|
||||
def postmaster_start_time(self):
|
||||
try:
|
||||
query = "SELECT " + self.POSTMASTER_START_TIME
|
||||
if current_thread().ident == self.__thread_ident:
|
||||
return self.query(query).fetchone()[0]
|
||||
with self.connection().cursor() as cursor:
|
||||
cursor.execute(query)
|
||||
return cursor.fetchone()[0]
|
||||
except psycopg2.Error:
|
||||
return None
|
||||
|
||||
def last_operation(self):
|
||||
return str(self._wal_position(self.is_leader(), self._cluster_info_state_get('wal_position'),
|
||||
self.received_location(), self.replayed_location()))
|
||||
|
||||
def configure_server_parameters(self):
|
||||
self._major_version = self.get_major_version()
|
||||
self.config.setup_server_parameters()
|
||||
return True
|
||||
|
||||
def move_data_directory(self):
|
||||
if os.path.isdir(self._data_dir) and not self.is_running():
|
||||
try:
|
||||
new_name = '{0}_{1}'.format(self._data_dir, time.strftime('%Y-%m-%d-%H-%M-%S'))
|
||||
logger.info('renaming data directory to %s', new_name)
|
||||
os.rename(self._data_dir, new_name)
|
||||
except OSError:
|
||||
logger.exception("Could not rename data directory %s", self._data_dir)
|
||||
|
||||
def remove_data_directory(self):
|
||||
self.set_role('uninitialized')
|
||||
logger.info('Removing data directory: %s', self._data_dir)
|
||||
try:
|
||||
if os.path.islink(self._data_dir):
|
||||
os.unlink(self._data_dir)
|
||||
elif not os.path.exists(self._data_dir):
|
||||
return
|
||||
elif os.path.isfile(self._data_dir):
|
||||
os.remove(self._data_dir)
|
||||
elif os.path.isdir(self._data_dir):
|
||||
|
||||
# let's see if pg_xlog|pg_wal is a symlink, in this case we
|
||||
# should clean the target
|
||||
for pg_wal_dir in ('pg_xlog', 'pg_wal'):
|
||||
pg_wal_path = os.path.join(self._data_dir, pg_wal_dir)
|
||||
if os.path.exists(pg_wal_path) and os.path.islink(pg_wal_path):
|
||||
pg_wal_realpath = os.path.realpath(pg_wal_path)
|
||||
logger.info('Removing WAL directory: %s', pg_wal_realpath)
|
||||
shutil.rmtree(pg_wal_realpath)
|
||||
# Remove user defined tablespace directory
|
||||
pg_tblsp_dir = os.path.join(self._data_dir, 'pg_tblspc')
|
||||
if os.path.exists(pg_tblsp_dir):
|
||||
for tsdn in os.listdir(pg_tblsp_dir):
|
||||
pg_tsp_path = os.path.join(pg_tblsp_dir, tsdn)
|
||||
if parse_int(tsdn) and os.path.islink(pg_tsp_path):
|
||||
pg_tsp_rpath = os.path.realpath(pg_tsp_path)
|
||||
logger.info('Removing user defined tablespace directory: %s', pg_tsp_rpath)
|
||||
shutil.rmtree(pg_tsp_rpath, ignore_errors=True)
|
||||
|
||||
shutil.rmtree(self._data_dir)
|
||||
except (IOError, OSError):
|
||||
logger.exception('Could not remove data directory %s', self._data_dir)
|
||||
self.move_data_directory()
|
||||
|
||||
def pick_synchronous_standby(self, cluster):
|
||||
"""Finds the best candidate to be the synchronous standby.
|
||||
|
||||
Current synchronous standby is always preferred, unless it has disconnected or does not want to be a
|
||||
synchronous standby any longer.
|
||||
|
||||
:returns tuple of candidate name or None, and bool showing if the member is the active synchronous standby.
|
||||
"""
|
||||
current = cluster.sync.sync_standby
|
||||
current = current.lower() if current else current
|
||||
members = {m.name.lower(): m for m in cluster.members}
|
||||
candidates = []
|
||||
# Pick candidates based on who has flushed WAL farthest.
|
||||
# TODO: for synchronous_commit = remote_write we actually want to order on write_location
|
||||
for app_name, state, sync_state in self.query(
|
||||
"SELECT pg_catalog.lower(application_name), state, sync_state"
|
||||
" FROM pg_catalog.pg_stat_replication"
|
||||
" ORDER BY flush_{0} DESC".format(self.lsn_name)):
|
||||
member = members.get(app_name)
|
||||
if state != 'streaming' or not member or member.tags.get('nosync', False):
|
||||
continue
|
||||
if sync_state == 'sync':
|
||||
return member.name, True
|
||||
if sync_state == 'potential' and app_name == current:
|
||||
# Prefer current even if not the best one any more to avoid indecisivness and spurious swaps.
|
||||
return cluster.sync.sync_standby, False
|
||||
if sync_state in ('async', 'potential'):
|
||||
candidates.append(member.name)
|
||||
|
||||
if candidates:
|
||||
return candidates[0], False
|
||||
return None, False
|
||||
|
||||
def schedule_sanity_checks_after_pause(self):
|
||||
"""
|
||||
After coming out of pause we have to:
|
||||
1. sync replication slots, because it might happen that slots were removed
|
||||
2. get new 'Database system identifier' to make sure that it wasn't changed
|
||||
"""
|
||||
self.slots_handler.schedule()
|
||||
self._sysid = None
|
||||
@@ -0,0 +1,379 @@
|
||||
import logging
|
||||
import os
|
||||
import shlex
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from patroni.dcs import RemoteMember
|
||||
from patroni.utils import deep_compare
|
||||
from six import string_types
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Bootstrap(object):
|
||||
|
||||
def __init__(self, postgresql):
|
||||
self._postgresql = postgresql
|
||||
self._running_custom_bootstrap = False
|
||||
|
||||
@property
|
||||
def running_custom_bootstrap(self):
|
||||
return self._running_custom_bootstrap
|
||||
|
||||
@property
|
||||
def keep_existing_recovery_conf(self):
|
||||
return self._running_custom_bootstrap and self._keep_existing_recovery_conf
|
||||
|
||||
@staticmethod
|
||||
def process_user_options(tool, options, not_allowed_options, error_handler):
|
||||
user_options = []
|
||||
|
||||
def option_is_allowed(name):
|
||||
ret = name not in not_allowed_options
|
||||
if not ret:
|
||||
error_handler('{0} option for {1} is not allowed'.format(name, tool))
|
||||
return ret
|
||||
|
||||
if isinstance(options, dict):
|
||||
for k, v in options.items():
|
||||
if k and v:
|
||||
user_options.append('--{0}={1}'.format(k, v))
|
||||
elif isinstance(options, list):
|
||||
for opt in options:
|
||||
if isinstance(opt, string_types) and option_is_allowed(opt):
|
||||
user_options.append('--{0}'.format(opt))
|
||||
elif isinstance(opt, dict):
|
||||
keys = list(opt.keys())
|
||||
if len(keys) != 1 or not isinstance(opt[keys[0]], string_types) or not option_is_allowed(keys[0]):
|
||||
error_handler('Error when parsing {0} key-value option {1}: only one key-value is allowed'
|
||||
' and value should be a string'.format(tool, opt[keys[0]]))
|
||||
user_options.append('--{0}={1}'.format(keys[0], opt[keys[0]]))
|
||||
else:
|
||||
error_handler('Error when parsing {0} option {1}: value should be string value'
|
||||
' or a single key-value pair'.format(tool, opt))
|
||||
else:
|
||||
error_handler('{0} options must be list ot dict'.format(tool))
|
||||
return user_options
|
||||
|
||||
def _initdb(self, config):
|
||||
self._postgresql.set_state('initalizing new cluster')
|
||||
not_allowed_options = ('pgdata', 'nosync', 'pwfile', 'sync-only', 'version')
|
||||
|
||||
def error_handler(e):
|
||||
raise Exception(e)
|
||||
|
||||
options = self.process_user_options('initdb', config or [], not_allowed_options, error_handler)
|
||||
pwfile = None
|
||||
|
||||
if self._postgresql.config.superuser:
|
||||
if 'username' in self._postgresql.config.superuser:
|
||||
options.append('--username={0}'.format(self._postgresql.config.superuser['username']))
|
||||
if 'password' in self._postgresql.config.superuser:
|
||||
(fd, pwfile) = tempfile.mkstemp()
|
||||
os.write(fd, self._postgresql.config.superuser['password'].encode('utf-8'))
|
||||
os.close(fd)
|
||||
options.append('--pwfile={0}'.format(pwfile))
|
||||
options = ['-o', ' '.join(options)] if options else []
|
||||
|
||||
ret = self._postgresql.pg_ctl('initdb', *options)
|
||||
if pwfile:
|
||||
os.remove(pwfile)
|
||||
if ret:
|
||||
self._postgresql.configure_server_parameters()
|
||||
else:
|
||||
self._postgresql.set_state('initdb failed')
|
||||
return ret
|
||||
|
||||
def _post_restore(self):
|
||||
self._postgresql.config.restore_configuration_files()
|
||||
self._postgresql.configure_server_parameters()
|
||||
|
||||
# make sure there is no trigger file or postgres will be automatically promoted
|
||||
trigger_file = 'promote_trigger_file' if self._postgresql.major_version >= 120000 else 'trigger_file'
|
||||
trigger_file = self._postgresql.config.get('recovery_conf', {}).get(trigger_file) or 'promote'
|
||||
trigger_file = os.path.abspath(os.path.join(self._postgresql.data_dir, trigger_file))
|
||||
if os.path.exists(trigger_file):
|
||||
os.unlink(trigger_file)
|
||||
|
||||
def _custom_bootstrap(self, config):
|
||||
self._postgresql.set_state('running custom bootstrap script')
|
||||
params = ['--scope=' + self._postgresql.scope, '--datadir=' + self._postgresql.data_dir]
|
||||
try:
|
||||
logger.info('Running custom bootstrap script: %s', config['command'])
|
||||
if self._postgresql.cancellable.call(shlex.split(config['command']) + params) != 0:
|
||||
self._postgresql.set_state('custom bootstrap failed')
|
||||
return False
|
||||
except Exception:
|
||||
logger.exception('Exception during custom bootstrap')
|
||||
return False
|
||||
self._post_restore()
|
||||
|
||||
if 'recovery_conf' in config:
|
||||
self._postgresql.config.write_recovery_conf(config['recovery_conf'])
|
||||
elif not self.keep_existing_recovery_conf:
|
||||
self._postgresql.config.remove_recovery_conf()
|
||||
return True
|
||||
|
||||
def call_post_bootstrap(self, config):
|
||||
"""
|
||||
runs a script after initdb or custom bootstrap script is called and waits until completion.
|
||||
"""
|
||||
cmd = config.get('post_bootstrap') or config.get('post_init')
|
||||
if cmd:
|
||||
r = self._postgresql.config.local_connect_kwargs
|
||||
connstring = self._postgresql.config.format_dsn(r, True)
|
||||
if 'host' not in r:
|
||||
# https://www.postgresql.org/docs/current/static/libpq-pgpass.html
|
||||
# A host name of localhost matches both TCP (host name localhost) and Unix domain socket
|
||||
# (pghost empty or the default socket directory) connections coming from the local machine.
|
||||
r['host'] = 'localhost' # set it to localhost to write into pgpass
|
||||
|
||||
env = self._postgresql.config.write_pgpass(r) if 'password' in r else None
|
||||
env['PGOPTIONS'] = '-c synchronous_commit=local'
|
||||
|
||||
try:
|
||||
ret = self._postgresql.cancellable.call(shlex.split(cmd) + [connstring], env=env)
|
||||
except OSError:
|
||||
logger.error('post_init script %s failed', cmd)
|
||||
return False
|
||||
if ret != 0:
|
||||
logger.error('post_init script %s returned non-zero code %d', cmd, ret)
|
||||
return False
|
||||
return True
|
||||
|
||||
def create_replica(self, clone_member):
|
||||
"""
|
||||
create the replica according to the replica_method
|
||||
defined by the user. this is a list, so we need to
|
||||
loop through all methods the user supplies
|
||||
"""
|
||||
|
||||
self._postgresql.set_state('creating replica')
|
||||
self._postgresql.schedule_sanity_checks_after_pause()
|
||||
|
||||
is_remote_master = isinstance(clone_member, RemoteMember)
|
||||
|
||||
# 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 = (clone_member.create_replica_methods if is_remote_master
|
||||
else self._postgresql.create_replica_methods) or ['basebackup']
|
||||
|
||||
if clone_member and clone_member.conn_url:
|
||||
r = clone_member.conn_kwargs(self._postgresql.config.replication)
|
||||
# add the credentials to connect to the replica origin to pgpass.
|
||||
env = self._postgresql.config.write_pgpass(r)
|
||||
connstring = self._postgresql.config.format_dsn(r, True)
|
||||
else:
|
||||
connstring = ''
|
||||
env = os.environ.copy()
|
||||
# if we don't have any source, leave only replica methods that work without it
|
||||
replica_methods = [r for r in replica_methods
|
||||
if self._postgresql.replica_method_can_work_without_replication_connection(r)]
|
||||
|
||||
# go through them in priority order
|
||||
ret = 1
|
||||
for replica_method in replica_methods:
|
||||
if self._postgresql.cancellable.is_cancelled:
|
||||
break
|
||||
|
||||
method_config = self._postgresql.replica_method_options(replica_method)
|
||||
|
||||
# if the method is basebackup, then use the built-in
|
||||
if replica_method == "basebackup":
|
||||
ret = self.basebackup(connstring, env, method_config)
|
||||
if ret == 0:
|
||||
logger.info("replica has been created using basebackup")
|
||||
# if basebackup succeeds, exit with success
|
||||
break
|
||||
else:
|
||||
if not self._postgresql.data_directory_empty():
|
||||
if method_config.get('keep_data', False):
|
||||
logger.info('Leaving data directory uncleaned')
|
||||
else:
|
||||
self._postgresql.remove_data_directory()
|
||||
|
||||
cmd = replica_method
|
||||
# user-defined method; check for configuration
|
||||
# not required, actually
|
||||
if method_config:
|
||||
# look to see if the user has supplied a full command path
|
||||
# if not, use the method name as the command
|
||||
cmd = method_config.pop('command', cmd)
|
||||
|
||||
# add the default parameters
|
||||
if not method_config.get('no_params', False):
|
||||
method_config.update({"scope": self._postgresql.scope,
|
||||
"role": "replica",
|
||||
"datadir": self._postgresql.data_dir,
|
||||
"connstring": connstring})
|
||||
else:
|
||||
for param in ('no_params', 'no_master', 'keep_data'):
|
||||
method_config.pop(param, None)
|
||||
params = ["--{0}={1}".format(arg, val) for arg, val in method_config.items()]
|
||||
try:
|
||||
# call script with the full set of parameters
|
||||
ret = self._postgresql.cancellable.call(shlex.split(cmd) + params, env=env)
|
||||
# if we succeeded, stop
|
||||
if ret == 0:
|
||||
logger.info('replica has been created using %s', replica_method)
|
||||
break
|
||||
else:
|
||||
logger.error('Error creating replica using method %s: %s exited with code=%s',
|
||||
replica_method, cmd, ret)
|
||||
except Exception:
|
||||
logger.exception('Error creating replica using method %s', replica_method)
|
||||
ret = 1
|
||||
|
||||
self._postgresql.set_state('stopped')
|
||||
return ret
|
||||
|
||||
def basebackup(self, conn_url, env, options):
|
||||
# creates a replica data dir using pg_basebackup.
|
||||
# this is the default, built-in create_replica_methods
|
||||
# tries twice, then returns failure (as 1)
|
||||
# uses "stream" as the xlog-method to avoid sync issues
|
||||
# supports additional user-supplied options, those are not validated
|
||||
maxfailures = 2
|
||||
ret = 1
|
||||
not_allowed_options = ('pgdata', 'format', 'wal-method', 'xlog-method', 'gzip',
|
||||
'version', 'compress', 'dbname', 'host', 'port', 'username', 'password')
|
||||
user_options = self.process_user_options('basebackup', options, not_allowed_options, logger.error)
|
||||
|
||||
for bbfailures in range(0, maxfailures):
|
||||
if self._postgresql.cancellable.is_cancelled:
|
||||
break
|
||||
if not self._postgresql.data_directory_empty():
|
||||
self._postgresql.remove_data_directory()
|
||||
try:
|
||||
ret = self._postgresql.cancellable.call([self._postgresql.pgcommand('pg_basebackup'),
|
||||
'--pgdata=' + self._postgresql.data_dir, '-X', 'stream',
|
||||
'--dbname=' + conn_url] + user_options, env=env)
|
||||
if ret == 0:
|
||||
break
|
||||
else:
|
||||
logger.error('Error when fetching backup: pg_basebackup exited with code=%s', ret)
|
||||
|
||||
except Exception as e:
|
||||
logger.error('Error when fetching backup with pg_basebackup: %s', e)
|
||||
|
||||
if bbfailures < maxfailures - 1:
|
||||
logger.warning('Trying again in 5 seconds')
|
||||
time.sleep(5)
|
||||
|
||||
return ret
|
||||
|
||||
def clone(self, clone_member):
|
||||
"""
|
||||
- initialize the replica from an existing member (master or replica)
|
||||
- initialize the replica using the replica creation method that
|
||||
works without the replication connection (i.e. restore from on-disk
|
||||
base backup)
|
||||
"""
|
||||
|
||||
ret = self.create_replica(clone_member) == 0
|
||||
if ret:
|
||||
self._post_restore()
|
||||
return ret
|
||||
|
||||
def bootstrap(self, config):
|
||||
""" Initialize a new node from scratch and start it. """
|
||||
pg_hba = config.get('pg_hba', [])
|
||||
method = config.get('method') or 'initdb'
|
||||
if method != 'initdb' and method in config and 'command' in config[method]:
|
||||
self._keep_existing_recovery_conf = config[method].get('keep_existing_recovery_conf')
|
||||
self._running_custom_bootstrap = True
|
||||
do_initialize = self._custom_bootstrap
|
||||
else:
|
||||
method = 'initdb'
|
||||
do_initialize = self._initdb
|
||||
return do_initialize(config.get(method)) and self._postgresql.config.append_pg_hba(pg_hba) \
|
||||
and self._postgresql.config.save_configuration_files() and self._postgresql.start()
|
||||
|
||||
def create_or_update_role(self, name, password, options):
|
||||
options = list(map(str.upper, options))
|
||||
if 'NOLOGIN' not in options and 'LOGIN' not in options:
|
||||
options.append('LOGIN')
|
||||
|
||||
params = [name]
|
||||
if password:
|
||||
options.extend(['PASSWORD', '%s'])
|
||||
params.extend([password, password])
|
||||
|
||||
sql = """DO $$
|
||||
BEGIN
|
||||
SET local synchronous_commit = 'local';
|
||||
PERFORM * FROM pg_authid WHERE rolname = %s;
|
||||
IF FOUND THEN
|
||||
ALTER ROLE "{0}" WITH {1};
|
||||
ELSE
|
||||
CREATE ROLE "{0}" WITH {1};
|
||||
END IF;
|
||||
END;$$""".format(name, ' '.join(options))
|
||||
self._postgresql.query('SET log_statement TO none')
|
||||
self._postgresql.query('SET log_min_duration_statement TO -1')
|
||||
self._postgresql.query("SET log_min_error_statement TO 'log'")
|
||||
try:
|
||||
self._postgresql.query(sql, *params)
|
||||
finally:
|
||||
self._postgresql.query('RESET log_min_error_statement')
|
||||
self._postgresql.query('RESET log_min_duration_statement')
|
||||
self._postgresql.query('RESET log_statement')
|
||||
|
||||
def post_bootstrap(self, config, task):
|
||||
try:
|
||||
postgresql = self._postgresql
|
||||
superuser = postgresql.config.superuser
|
||||
if 'username' in superuser and 'password' in superuser:
|
||||
self.create_or_update_role(superuser['username'], superuser['password'], ['SUPERUSER'])
|
||||
|
||||
task.complete(self.call_post_bootstrap(config))
|
||||
if task.result:
|
||||
replication = postgresql.config.replication
|
||||
self.create_or_update_role(replication['username'], replication.get('password'), ['REPLICATION'])
|
||||
|
||||
rewind = postgresql.config.rewind_credentials
|
||||
if not deep_compare(rewind, superuser):
|
||||
self.create_or_update_role(rewind['username'], rewind.get('password'), [])
|
||||
for f in ('pg_ls_dir(text, boolean, boolean)', 'pg_stat_file(text, boolean)',
|
||||
'pg_read_binary_file(text)', 'pg_read_binary_file(text, bigint, bigint, boolean)'):
|
||||
sql = """DO $$
|
||||
BEGIN
|
||||
SET local synchronous_commit = 'local';
|
||||
GRANT EXECUTE ON function pg_catalog.{0} TO "{1}";
|
||||
END;$$""".format(f, rewind['username'])
|
||||
postgresql.query(sql)
|
||||
|
||||
for name, value in (config.get('users') or {}).items():
|
||||
if all(name != a.get('username') for a in (superuser, replication, rewind)):
|
||||
self.create_or_update_role(name, value.get('password'), value.get('options', []))
|
||||
|
||||
# We were doing a custom bootstrap instead of running initdb, therefore we opened trust
|
||||
# access from certain addresses to be able to reach cluster and change password
|
||||
if self._running_custom_bootstrap:
|
||||
self._running_custom_bootstrap = False
|
||||
# If we don't have custom configuration for pg_hba.conf we need to restore original file
|
||||
if not postgresql.config.get('pg_hba'):
|
||||
os.unlink(postgresql.config.pg_hba_conf)
|
||||
postgresql.config.restore_configuration_files()
|
||||
postgresql.config.write_postgresql_conf()
|
||||
postgresql.config.replace_pg_ident()
|
||||
|
||||
# at this point there should be no recovery.conf
|
||||
postgresql.config.remove_recovery_conf()
|
||||
|
||||
if postgresql.config.hba_file:
|
||||
postgresql.restart()
|
||||
else:
|
||||
postgresql.config.replace_pg_hba()
|
||||
if postgresql.pending_restart:
|
||||
postgresql.restart()
|
||||
else:
|
||||
postgresql.reload()
|
||||
time.sleep(1) # give a time to postgres to "reload" configuration files
|
||||
postgresql.connection().close() # close connection to reconnect with a new password
|
||||
except Exception:
|
||||
logger.exception('post_bootstrap')
|
||||
task.complete(False)
|
||||
return task.result
|
||||
@@ -0,0 +1,36 @@
|
||||
import logging
|
||||
|
||||
from patroni.postgresql.cancellable import CancellableExecutor
|
||||
from threading import Condition, Thread
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CallbackExecutor(CancellableExecutor, Thread):
|
||||
|
||||
def __init__(self):
|
||||
CancellableExecutor.__init__(self)
|
||||
Thread.__init__(self)
|
||||
self.daemon = True
|
||||
self._cmd = None
|
||||
self._condition = Condition()
|
||||
self.start()
|
||||
|
||||
def call(self, cmd):
|
||||
self._kill_process()
|
||||
with self._condition:
|
||||
self._cmd = cmd
|
||||
self._condition.notify()
|
||||
|
||||
def run(self):
|
||||
while True:
|
||||
with self._condition:
|
||||
if self._cmd is None:
|
||||
self._condition.wait()
|
||||
cmd, self._cmd = self._cmd, None
|
||||
|
||||
with self._lock:
|
||||
if not self._start_process(cmd, close_fds=True):
|
||||
continue
|
||||
self._process.wait()
|
||||
self._kill_children()
|
||||
@@ -0,0 +1,125 @@
|
||||
import logging
|
||||
import psutil
|
||||
import subprocess
|
||||
|
||||
from patroni.exceptions import PostgresException
|
||||
from patroni.utils import polling_loop
|
||||
from threading import Lock
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CancellableExecutor(object):
|
||||
|
||||
def __init__(self):
|
||||
self._process = None
|
||||
self._process_cmd = None
|
||||
self._process_children = []
|
||||
self._lock = Lock()
|
||||
|
||||
def _start_process(self, cmd, *args, **kwargs):
|
||||
"""This method must be executed only when the `_lock` is acquired"""
|
||||
|
||||
try:
|
||||
self._process_children = []
|
||||
self._process_cmd = cmd
|
||||
self._process = psutil.Popen(cmd, *args, **kwargs)
|
||||
except Exception:
|
||||
return logger.exception('Failed to execute %s', cmd)
|
||||
return True
|
||||
|
||||
def _kill_process(self):
|
||||
with self._lock:
|
||||
if self._process is not None and self._process.is_running() and not self._process_children:
|
||||
try:
|
||||
self._process.suspend() # Suspend the process before getting list of childrens
|
||||
except psutil.Error as e:
|
||||
logger.info('Failed to suspend the process: %s', e.msg)
|
||||
|
||||
try:
|
||||
self._process_children = self._process.children(recursive=True)
|
||||
except psutil.Error:
|
||||
pass
|
||||
|
||||
try:
|
||||
self._process.kill()
|
||||
logger.warning('Killed %s because it was still running', self._process_cmd)
|
||||
except psutil.NoSuchProcess:
|
||||
pass
|
||||
except psutil.AccessDenied as e:
|
||||
logger.warning('Failed to kill the process: %s', e.msg)
|
||||
|
||||
def _kill_children(self):
|
||||
waitlist = []
|
||||
with self._lock:
|
||||
for child in self._process_children:
|
||||
try:
|
||||
child.kill()
|
||||
except psutil.NoSuchProcess:
|
||||
continue
|
||||
except psutil.AccessDenied as e:
|
||||
logger.info('Failed to kill child process: %s', e.msg)
|
||||
waitlist.append(child)
|
||||
psutil.wait_procs(waitlist)
|
||||
|
||||
|
||||
class CancellableSubprocess(CancellableExecutor):
|
||||
|
||||
def __init__(self):
|
||||
super(CancellableSubprocess, self).__init__()
|
||||
self._is_cancelled = False
|
||||
|
||||
def call(self, *args, **kwargs):
|
||||
for s in ('stdin', 'stdout', 'stderr'):
|
||||
kwargs.pop(s, None)
|
||||
|
||||
communicate = kwargs.pop('communicate', None)
|
||||
if isinstance(communicate, dict):
|
||||
input_data = communicate.get('input')
|
||||
if input_data:
|
||||
if input_data[-1] != '\n':
|
||||
input_data += '\n'
|
||||
input_data = input_data.encode('utf-8')
|
||||
kwargs['stdin'] = subprocess.PIPE
|
||||
kwargs['stdout'] = subprocess.PIPE
|
||||
kwargs['stderr'] = subprocess.PIPE
|
||||
|
||||
try:
|
||||
with self._lock:
|
||||
if self._is_cancelled:
|
||||
raise PostgresException('cancelled')
|
||||
|
||||
self._is_cancelled = False
|
||||
started = self._start_process(*args, **kwargs)
|
||||
|
||||
if started:
|
||||
if isinstance(communicate, dict):
|
||||
communicate['stdout'], communicate['stderr'] = self._process.communicate(input_data)
|
||||
return self._process.wait()
|
||||
finally:
|
||||
with self._lock:
|
||||
self._process = None
|
||||
self._kill_children()
|
||||
|
||||
def reset_is_cancelled(self):
|
||||
with self._lock:
|
||||
self._is_cancelled = False
|
||||
|
||||
@property
|
||||
def is_cancelled(self):
|
||||
with self._lock:
|
||||
return self._is_cancelled
|
||||
|
||||
def cancel(self):
|
||||
with self._lock:
|
||||
self._is_cancelled = True
|
||||
if self._process is None or not self._process.is_running():
|
||||
return
|
||||
self._process.terminate()
|
||||
|
||||
for _ in polling_loop(10):
|
||||
with self._lock:
|
||||
if self._process is None or not self._process.is_running():
|
||||
return
|
||||
|
||||
self._kill_process()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
import logging
|
||||
import psycopg2
|
||||
|
||||
from contextlib import contextmanager
|
||||
from threading import Lock
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Connection(object):
|
||||
|
||||
def __init__(self):
|
||||
self._lock = Lock()
|
||||
self._connection = None
|
||||
self._cursor_holder = None
|
||||
|
||||
def set_conn_kwargs(self, conn_kwargs):
|
||||
self._conn_kwargs = conn_kwargs
|
||||
|
||||
def get(self):
|
||||
with self._lock:
|
||||
if not self._connection or self._connection.closed != 0:
|
||||
self._connection = psycopg2.connect(**self._conn_kwargs)
|
||||
self._connection.autocommit = True
|
||||
self.server_version = self._connection.server_version
|
||||
return self._connection
|
||||
|
||||
def cursor(self):
|
||||
if not self._cursor_holder or self._cursor_holder.closed or self._cursor_holder.connection.closed != 0:
|
||||
logger.info("establishing a new patroni connection to the postgres cluster")
|
||||
self._cursor_holder = self.get().cursor()
|
||||
return self._cursor_holder
|
||||
|
||||
def close(self):
|
||||
if self._connection and self._connection.closed == 0:
|
||||
self._connection.close()
|
||||
logger.info("closed patroni connection to the postgresql cluster")
|
||||
self._cursor_holder = self._connection = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_connection_cursor(**kwargs):
|
||||
with psycopg2.connect(**kwargs) as conn:
|
||||
conn.autocommit = True
|
||||
with conn.cursor() as cur:
|
||||
yield cur
|
||||
@@ -0,0 +1,70 @@
|
||||
import logging
|
||||
|
||||
from patroni.exceptions import PostgresException
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def postgres_version_to_int(pg_version):
|
||||
"""Convert the server_version to integer
|
||||
|
||||
>>> postgres_version_to_int('9.5.3')
|
||||
90503
|
||||
>>> postgres_version_to_int('9.3.13')
|
||||
90313
|
||||
>>> postgres_version_to_int('10.1')
|
||||
100001
|
||||
>>> postgres_version_to_int('10') # doctest: +IGNORE_EXCEPTION_DETAIL
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 10'
|
||||
>>> postgres_version_to_int('9.6') # doctest: +IGNORE_EXCEPTION_DETAIL
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 9.6'
|
||||
>>> postgres_version_to_int('a.b.c') # doctest: +IGNORE_EXCEPTION_DETAIL
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
PostgresException: 'Invalid PostgreSQL version: a.b.c'
|
||||
"""
|
||||
|
||||
try:
|
||||
components = list(map(int, pg_version.split('.')))
|
||||
except ValueError:
|
||||
raise PostgresException('Invalid PostgreSQL version: {0}'.format(pg_version))
|
||||
|
||||
if len(components) < 2 or len(components) == 2 and components[0] < 10 or len(components) > 3:
|
||||
raise PostgresException('Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: {0}'.format(pg_version))
|
||||
|
||||
if len(components) == 2:
|
||||
# new style verion numbers, i.e. 10.1 becomes 100001
|
||||
components.insert(1, 0)
|
||||
|
||||
return int(''.join('{0:02d}'.format(c) for c in components))
|
||||
|
||||
|
||||
def postgres_major_version_to_int(pg_version):
|
||||
"""
|
||||
>>> postgres_major_version_to_int('10')
|
||||
100000
|
||||
>>> postgres_major_version_to_int('9.6')
|
||||
90600
|
||||
"""
|
||||
return postgres_version_to_int(pg_version + '.0')
|
||||
|
||||
|
||||
def parse_lsn(lsn):
|
||||
t = lsn.split('/')
|
||||
return int(t[0], 16) * 0x100000000 + int(t[1], 16)
|
||||
|
||||
|
||||
def parse_history(data):
|
||||
for line in data.split('\n'):
|
||||
values = line.strip().split('\t')
|
||||
if len(values) == 3:
|
||||
try:
|
||||
values[0] = int(values[0])
|
||||
values[1] = parse_lsn(values[1])
|
||||
yield values
|
||||
except (IndexError, ValueError):
|
||||
logger.exception('Exception when parsing timeline history line "%s"', values)
|
||||
@@ -0,0 +1,246 @@
|
||||
import logging
|
||||
import multiprocessing
|
||||
import os
|
||||
import psutil
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from patroni import PATRONI_ENV_PREFIX, KUBERNETES_ENV_PREFIX
|
||||
|
||||
# avoid spawning the resource tracker process
|
||||
if sys.version_info >= (3, 8): # pragma: no cover
|
||||
import multiprocessing.resource_tracker
|
||||
multiprocessing.resource_tracker.getfd = lambda: 0
|
||||
elif sys.version_info >= (3, 4): # pragma: no cover
|
||||
import multiprocessing.semaphore_tracker
|
||||
multiprocessing.semaphore_tracker.getfd = lambda: 0
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STOP_SIGNALS = {
|
||||
'smart': 'TERM',
|
||||
'fast': 'INT',
|
||||
'immediate': 'QUIT',
|
||||
}
|
||||
|
||||
|
||||
def pg_ctl_start(conn, cmdline, env):
|
||||
if os.name != 'nt':
|
||||
os.setsid()
|
||||
try:
|
||||
postmaster = subprocess.Popen(cmdline, close_fds=True, env=env)
|
||||
conn.send(postmaster.pid)
|
||||
except Exception:
|
||||
logger.exception('Failed to execute %s', cmdline)
|
||||
conn.send(None)
|
||||
conn.close()
|
||||
|
||||
|
||||
class PostmasterProcess(psutil.Process):
|
||||
|
||||
def __init__(self, pid):
|
||||
self.is_single_user = False
|
||||
if pid < 0:
|
||||
pid = -pid
|
||||
self.is_single_user = True
|
||||
super(PostmasterProcess, self).__init__(pid)
|
||||
|
||||
@staticmethod
|
||||
def _read_postmaster_pidfile(data_dir):
|
||||
"""Reads and parses postmaster.pid from the data directory
|
||||
|
||||
:returns dictionary of values if successful, empty dictionary otherwise
|
||||
"""
|
||||
pid_line_names = ['pid', 'data_dir', 'start_time', 'port', 'socket_dir', 'listen_addr', 'shmem_key']
|
||||
try:
|
||||
with open(os.path.join(data_dir, 'postmaster.pid')) as f:
|
||||
return {name: line.rstrip('\n') for name, line in zip(pid_line_names, f)}
|
||||
except IOError:
|
||||
return {}
|
||||
|
||||
def _is_postmaster_process(self):
|
||||
try:
|
||||
start_time = int(self._postmaster_pid.get('start_time', 0))
|
||||
if start_time and abs(self.create_time() - start_time) > 3:
|
||||
logger.info('Process %s is not postmaster, too much difference between PID file start time %s and '
|
||||
'process start time %s', self.pid, self.create_time(), start_time)
|
||||
return False
|
||||
except ValueError:
|
||||
logger.warning('Garbage start time value in pid file: %r', self._postmaster_pid.get('start_time'))
|
||||
|
||||
# Extra safety check. The process can't be ourselves, our parent or our direct child.
|
||||
if self.pid == os.getpid() or self.pid == os.getppid() or self.ppid() == os.getpid():
|
||||
logger.info('Patroni (pid=%s, ppid=%s), "fake postmaster" (pid=%s, ppid=%s)',
|
||||
os.getpid(), os.getppid(), self.pid, self.ppid())
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def _from_pidfile(cls, data_dir):
|
||||
postmaster_pid = PostmasterProcess._read_postmaster_pidfile(data_dir)
|
||||
try:
|
||||
pid = int(postmaster_pid.get('pid', 0))
|
||||
if pid:
|
||||
proc = cls(pid)
|
||||
proc._postmaster_pid = postmaster_pid
|
||||
return proc
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def from_pidfile(data_dir):
|
||||
try:
|
||||
proc = PostmasterProcess._from_pidfile(data_dir)
|
||||
return proc if proc and proc._is_postmaster_process() else None
|
||||
except psutil.NoSuchProcess:
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def from_pid(cls, pid):
|
||||
try:
|
||||
return cls(pid)
|
||||
except psutil.NoSuchProcess:
|
||||
return None
|
||||
|
||||
def signal_kill(self):
|
||||
"""to suspend and kill postmaster and all children
|
||||
|
||||
:returns True if postmaster and children are killed, False if error
|
||||
"""
|
||||
try:
|
||||
self.suspend()
|
||||
except psutil.NoSuchProcess:
|
||||
return True
|
||||
except psutil.Error as e:
|
||||
logger.warning('Failed to suspend postmaster: %s', e)
|
||||
|
||||
try:
|
||||
children = self.children(recursive=True)
|
||||
except psutil.NoSuchProcess:
|
||||
return True
|
||||
except psutil.Error as e:
|
||||
logger.warning('Failed to get a list of postmaster children: %s', e)
|
||||
children = []
|
||||
|
||||
try:
|
||||
self.kill()
|
||||
except psutil.NoSuchProcess:
|
||||
return True
|
||||
except psutil.Error as e:
|
||||
logger.warning('Could not kill postmaster: %s', e)
|
||||
return False
|
||||
|
||||
for child in children:
|
||||
try:
|
||||
child.kill()
|
||||
except psutil.Error:
|
||||
pass
|
||||
psutil.wait_procs(children + [self])
|
||||
return True
|
||||
|
||||
def signal_stop(self, mode, pg_ctl='pg_ctl'):
|
||||
"""Signal postmaster process to stop
|
||||
|
||||
:returns None if signaled, True if process is already gone, False if error
|
||||
"""
|
||||
if self.is_single_user:
|
||||
logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid))
|
||||
return False
|
||||
if os.name != 'posix':
|
||||
return self.pg_ctl_kill(mode, pg_ctl)
|
||||
try:
|
||||
self.send_signal(getattr(signal, 'SIG' + STOP_SIGNALS[mode]))
|
||||
except psutil.NoSuchProcess:
|
||||
return True
|
||||
except psutil.AccessDenied as e:
|
||||
logger.warning("Could not send stop signal to PostgreSQL (error: {0})".format(e))
|
||||
return False
|
||||
|
||||
return None
|
||||
|
||||
def pg_ctl_kill(self, mode, pg_ctl):
|
||||
try:
|
||||
status = subprocess.call([pg_ctl, "kill", STOP_SIGNALS[mode], str(self.pid)])
|
||||
except OSError:
|
||||
return False
|
||||
if status == 0:
|
||||
return None
|
||||
else:
|
||||
return not self.is_running()
|
||||
|
||||
def wait_for_user_backends_to_close(self):
|
||||
# These regexps are cross checked against versions PostgreSQL 9.1 .. 11
|
||||
aux_proc_re = re.compile("(?:postgres:)( .*:)? (?:(?:archiver|startup|autovacuum launcher|autovacuum worker|"
|
||||
"checkpointer|logger|stats collector|wal receiver|wal writer|writer)(?: process )?|"
|
||||
"walreceiver|wal sender process|walsender|walwriter|background writer|"
|
||||
"logical replication launcher|logical replication worker for|bgworker:) ")
|
||||
|
||||
try:
|
||||
children = self.children()
|
||||
except psutil.Error:
|
||||
return logger.debug('Failed to get list of postmaster children')
|
||||
|
||||
user_backends = []
|
||||
user_backends_cmdlines = []
|
||||
for child in children:
|
||||
try:
|
||||
cmdline = child.cmdline()[0]
|
||||
if not aux_proc_re.match(cmdline):
|
||||
user_backends.append(child)
|
||||
user_backends_cmdlines.append(cmdline)
|
||||
except psutil.NoSuchProcess:
|
||||
pass
|
||||
if user_backends:
|
||||
logger.debug('Waiting for user backends %s to close', ', '.join(user_backends_cmdlines))
|
||||
psutil.wait_procs(user_backends)
|
||||
logger.debug("Backends closed")
|
||||
|
||||
@staticmethod
|
||||
def start(pgcommand, data_dir, conf, options):
|
||||
# Unfortunately `pg_ctl start` does not return postmaster pid to us. Without this information
|
||||
# it is hard to know the current state of postgres startup, so we had to reimplement pg_ctl start
|
||||
# in python. It will start postgres, wait for port to be open and wait until postgres will start
|
||||
# accepting connections.
|
||||
# Important!!! We can't just start postgres using subprocess.Popen, because in this case it
|
||||
# will be our child for the rest of our live and we will have to take care of it (`waitpid`).
|
||||
# So we will use the same approach as pg_ctl uses: start a new process, which will start postgres.
|
||||
# This process will write postmaster pid to stdout and exit immediately. Now it's responsibility
|
||||
# of init process to take care about postmaster.
|
||||
# In order to make everything portable we can't use fork&exec approach here, so we will call
|
||||
# ourselves and pass list of arguments which must be used to start postgres.
|
||||
# On Windows, in order to run a side-by-side assembly the specified env must include a valid SYSTEMROOT.
|
||||
env = {p: os.environ[p] for p in os.environ if not p.startswith(
|
||||
PATRONI_ENV_PREFIX) and not p.startswith(KUBERNETES_ENV_PREFIX)}
|
||||
try:
|
||||
proc = PostmasterProcess._from_pidfile(data_dir)
|
||||
if proc and not proc._is_postmaster_process():
|
||||
# Upon start postmaster process performs various safety checks if there is a postmaster.pid
|
||||
# file in the data directory. Although Patroni already detected that the running process
|
||||
# corresponding to the postmaster.pid is not a postmaster, the new postmaster might fail
|
||||
# to start, because it thinks that postmaster.pid is already locked.
|
||||
# Important!!! Unlink of postmaster.pid isn't an option, because it has a lot of nasty race conditions.
|
||||
# Luckily there is a workaround to this problem, we can pass the pid from postmaster.pid
|
||||
# in the `PG_GRANDPARENT_PID` environment variable and postmaster will ignore it.
|
||||
logger.info("Telling pg_ctl that it is safe to ignore postmaster.pid for process %s", proc.pid)
|
||||
env['PG_GRANDPARENT_PID'] = str(proc.pid)
|
||||
except psutil.NoSuchProcess:
|
||||
pass
|
||||
cmdline = [pgcommand, '-D', data_dir, '--config-file={}'.format(conf)] + options
|
||||
logger.debug("Starting postgres: %s", " ".join(cmdline))
|
||||
ctx = multiprocessing.get_context('spawn') if sys.version_info >= (3, 4) else multiprocessing
|
||||
parent_conn, child_conn = ctx.Pipe(False)
|
||||
proc = ctx.Process(target=pg_ctl_start, args=(child_conn, cmdline, env))
|
||||
proc.start()
|
||||
pid = parent_conn.recv()
|
||||
proc.join()
|
||||
if pid is None:
|
||||
return
|
||||
logger.info('postmaster pid=%s', pid)
|
||||
|
||||
# TODO: In an extremely unlikely case, the process could have exited and the pid reassigned. The start
|
||||
# initiation time is not accurate enough to compare to create time as start time would also likely
|
||||
# be relatively close. We need the subprocess extract pid+start_time in a race free manner.
|
||||
return PostmasterProcess.from_pid(pid)
|
||||
@@ -0,0 +1,430 @@
|
||||
import logging
|
||||
import os
|
||||
import six
|
||||
import subprocess
|
||||
|
||||
from threading import Lock, Thread
|
||||
|
||||
from .connection import get_connection_cursor
|
||||
from .misc import parse_history, parse_lsn
|
||||
from ..async_executor import CriticalTask
|
||||
from ..dcs import Leader
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REWIND_STATUS = type('Enum', (), {'INITIAL': 0, 'CHECKPOINT': 1, 'CHECK': 2, 'NEED': 3,
|
||||
'NOT_NEED': 4, 'SUCCESS': 5, 'FAILED': 6})
|
||||
|
||||
|
||||
def format_lsn(lsn, full=False):
|
||||
template = '{0:X}/{1:08X}' if full else '{0:X}/{1:X}'
|
||||
return template.format(lsn >> 32, lsn & 0xFFFFFFFF)
|
||||
|
||||
|
||||
class Rewind(object):
|
||||
|
||||
def __init__(self, postgresql):
|
||||
self._postgresql = postgresql
|
||||
self._checkpoint_task_lock = Lock()
|
||||
self.reset_state()
|
||||
|
||||
@staticmethod
|
||||
def configuration_allows_rewind(data):
|
||||
return data.get('wal_log_hints setting', 'off') == 'on' or data.get('Data page checksum version', '0') != '0'
|
||||
|
||||
@property
|
||||
def can_rewind(self):
|
||||
""" check if pg_rewind executable is there and that pg_controldata indicates
|
||||
we have either wal_log_hints or checksums turned on
|
||||
"""
|
||||
# low-hanging fruit: check if pg_rewind configuration is there
|
||||
if not self._postgresql.config.get('use_pg_rewind'):
|
||||
return False
|
||||
|
||||
cmd = [self._postgresql.pgcommand('pg_rewind'), '--help']
|
||||
try:
|
||||
ret = subprocess.call(cmd, stdout=open(os.devnull, 'w'), stderr=subprocess.STDOUT)
|
||||
if ret != 0: # pg_rewind is not there, close up the shop and go home
|
||||
return False
|
||||
except OSError:
|
||||
return False
|
||||
return self.configuration_allows_rewind(self._postgresql.controldata())
|
||||
|
||||
@property
|
||||
def can_rewind_or_reinitialize_allowed(self):
|
||||
return self._postgresql.config.get('remove_data_directory_on_diverged_timelines') or self.can_rewind
|
||||
|
||||
def trigger_check_diverged_lsn(self):
|
||||
if self.can_rewind_or_reinitialize_allowed and self._state != REWIND_STATUS.NEED:
|
||||
self._state = REWIND_STATUS.CHECK
|
||||
|
||||
def check_leader_is_not_in_recovery(self, **kwargs):
|
||||
if not kwargs.get('database'):
|
||||
kwargs['database'] = self._postgresql.database
|
||||
try:
|
||||
with get_connection_cursor(connect_timeout=3, options='-c statement_timeout=2000', **kwargs) as cur:
|
||||
cur.execute('SELECT pg_catalog.pg_is_in_recovery()')
|
||||
if not cur.fetchone()[0]:
|
||||
return True
|
||||
logger.info('Leader is still in_recovery and therefore can\'t be used for rewind')
|
||||
except Exception:
|
||||
return logger.exception('Exception when working with leader')
|
||||
|
||||
def _get_checkpoint_end(self, timeline, lsn):
|
||||
"""The checkpoint record size in WAL depends on postgres major version and platform (memory alignment).
|
||||
Hence, the only reliable way to figure out where it ends, read the record from file with the help of pg_waldump
|
||||
and parse the output. We are trying to read two records, and expect that it wil fail to read the second one:
|
||||
`pg_waldump: fatal: error in WAL record at 0/182E220: invalid record length at 0/182E298: wanted 24, got 0`
|
||||
The error message contains information about LSN of the next record, which is exactly where checkpoint ends."""
|
||||
|
||||
cmd = self._postgresql.pgcommand('pg_{0}dump'.format(self._postgresql.wal_name))
|
||||
lsn8 = format_lsn(lsn, True)
|
||||
lsn = format_lsn(lsn)
|
||||
env = os.environ.copy()
|
||||
env.update(LANG='C', LC_ALL='C', PGDATA=self._postgresql.data_dir)
|
||||
try:
|
||||
waldump = subprocess.Popen([cmd, '-t', str(timeline), '-s', lsn, '-n', '2'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
|
||||
out, err = waldump.communicate()
|
||||
waldump.wait()
|
||||
except Exception as e:
|
||||
logger.error('Failed to execute `%s -t %s -s %s -n 2`: %r', cmd, timeline, lsn, e)
|
||||
else:
|
||||
out = out.decode('utf-8').rstrip().split('\n')
|
||||
err = err.decode('utf-8').rstrip().split('\n')
|
||||
pattern = 'error in WAL record at {0}: invalid record length at '.format(lsn)
|
||||
|
||||
if len(out) == 1 and len(err) == 1 and ', lsn: {0}, prev '.format(lsn8) in out[0] and pattern in err[0]:
|
||||
i = err[0].find(pattern) + len(pattern)
|
||||
j = err[0].find(": wanted ", i)
|
||||
if j > -1:
|
||||
try:
|
||||
return parse_lsn(err[0][i:j])
|
||||
except Exception as e:
|
||||
logger.error('Failed to parse lsn %s: %r', err[0][i:j], e)
|
||||
logger.error('Failed to parse `%s -t %s -s %s -n 2` output', cmd, timeline, lsn)
|
||||
logger.error(' stdout=%s', '\n'.join(out))
|
||||
logger.error(' stderr=%s', '\n'.join(err))
|
||||
|
||||
return 0
|
||||
|
||||
def _get_local_timeline_lsn_from_controldata(self):
|
||||
in_recovery = timeline = lsn = None
|
||||
data = self._postgresql.controldata()
|
||||
try:
|
||||
if data.get('Database cluster state') == 'shut down in recovery':
|
||||
in_recovery = True
|
||||
lsn = data.get('Minimum recovery ending location')
|
||||
timeline = int(data.get("Min recovery ending loc's timeline"))
|
||||
if lsn == '0/0' or timeline == 0: # it was a master when it crashed
|
||||
data['Database cluster state'] = 'shut down'
|
||||
if data.get('Database cluster state') == 'shut down':
|
||||
in_recovery = False
|
||||
lsn = data.get('Latest checkpoint location')
|
||||
timeline = int(data.get("Latest checkpoint's TimeLineID"))
|
||||
except (TypeError, ValueError):
|
||||
logger.exception('Failed to get local timeline and lsn from pg_controldata output')
|
||||
|
||||
if lsn is not None:
|
||||
try:
|
||||
lsn = parse_lsn(lsn)
|
||||
except (IndexError, ValueError) as e:
|
||||
logger.error('Exception when parsing lsn %s: %r', lsn, e)
|
||||
lsn = None
|
||||
|
||||
return in_recovery, timeline, lsn
|
||||
|
||||
def _get_local_timeline_lsn(self):
|
||||
if self._postgresql.is_running(): # if postgres is running - get timeline from replication connection
|
||||
in_recovery = True
|
||||
timeline = self._postgresql.received_timeline() or self._postgresql.get_replica_timeline()
|
||||
lsn = self._postgresql.replayed_location()
|
||||
else: # otherwise analyze pg_controldata output
|
||||
in_recovery, timeline, lsn = self._get_local_timeline_lsn_from_controldata()
|
||||
|
||||
log_lsn = format_lsn(lsn) if isinstance(lsn, six.integer_types) else lsn
|
||||
logger.info('Local timeline=%s lsn=%s', timeline, log_lsn)
|
||||
return in_recovery, timeline, lsn
|
||||
|
||||
@staticmethod
|
||||
def _log_master_history(history, i):
|
||||
start = max(0, i - 3)
|
||||
end = None if i + 4 >= len(history) else i + 2
|
||||
history_show = []
|
||||
|
||||
def format_history_line(line):
|
||||
return '{0}\t{1}\t{2}'.format(line[0], format_lsn(line[1]), line[2])
|
||||
|
||||
for line in history[start:end]:
|
||||
history_show.append(format_history_line(line))
|
||||
|
||||
if line != history[-1]:
|
||||
history_show.append('...')
|
||||
history_show.append(format_history_line(history[-1]))
|
||||
|
||||
logger.info('master: history=%s', '\n'.join(history_show))
|
||||
|
||||
def _check_timeline_and_lsn(self, leader):
|
||||
in_recovery, local_timeline, local_lsn = self._get_local_timeline_lsn()
|
||||
if local_timeline is None or local_lsn is None:
|
||||
return
|
||||
|
||||
if isinstance(leader, Leader):
|
||||
if leader.member.data.get('role') != 'master':
|
||||
return
|
||||
# standby cluster
|
||||
elif not self.check_leader_is_not_in_recovery(**leader.conn_kwargs(self._postgresql.config.replication)):
|
||||
return
|
||||
|
||||
history = need_rewind = None
|
||||
try:
|
||||
with self._postgresql.get_replication_connection_cursor(**leader.conn_kwargs()) as cur:
|
||||
cur.execute('IDENTIFY_SYSTEM')
|
||||
master_timeline = cur.fetchone()[1]
|
||||
logger.info('master_timeline=%s', master_timeline)
|
||||
if local_timeline > master_timeline: # Not always supported by pg_rewind
|
||||
need_rewind = True
|
||||
elif local_timeline == master_timeline:
|
||||
need_rewind = False
|
||||
elif master_timeline > 1:
|
||||
cur.execute('TIMELINE_HISTORY %s', (master_timeline,))
|
||||
history = bytes(cur.fetchone()[1]).decode('utf-8')
|
||||
logger.debug('master: history=%s', history)
|
||||
except Exception:
|
||||
return logger.exception('Exception when working with master via replication connection')
|
||||
|
||||
if history is not None:
|
||||
history = list(parse_history(history))
|
||||
for i, (parent_timeline, switchpoint, _) in enumerate(history):
|
||||
if parent_timeline == local_timeline:
|
||||
# We don't need to rewind when:
|
||||
# 1. for replica: replayed location is not ahead of switchpoint
|
||||
# 2. for the former primary: end of checkpoint record is the same as switchpoint
|
||||
if in_recovery:
|
||||
need_rewind = local_lsn > switchpoint
|
||||
elif local_lsn >= switchpoint:
|
||||
need_rewind = True
|
||||
else:
|
||||
need_rewind = switchpoint != self._get_checkpoint_end(local_timeline, local_lsn)
|
||||
break
|
||||
elif parent_timeline > local_timeline:
|
||||
break
|
||||
self._log_master_history(history, i)
|
||||
|
||||
self._state = need_rewind and REWIND_STATUS.NEED or REWIND_STATUS.NOT_NEED
|
||||
|
||||
def rewind_or_reinitialize_needed_and_possible(self, leader):
|
||||
if leader and leader.name != self._postgresql.name and leader.conn_url and self._state == REWIND_STATUS.CHECK:
|
||||
self._check_timeline_and_lsn(leader)
|
||||
return leader and leader.conn_url and self._state == REWIND_STATUS.NEED
|
||||
|
||||
def __checkpoint(self, task, wakeup):
|
||||
try:
|
||||
result = self._postgresql.checkpoint()
|
||||
except Exception as e:
|
||||
result = 'Exception: ' + str(e)
|
||||
with task:
|
||||
task.complete(not bool(result))
|
||||
if task.result:
|
||||
wakeup()
|
||||
|
||||
def ensure_checkpoint_after_promote(self, wakeup):
|
||||
"""After promote issue a CHECKPOINT from a new thread and asynchronously check the result.
|
||||
In case if CHECKPOINT failed, just check that timeline in pg_control was updated."""
|
||||
|
||||
if self._state == REWIND_STATUS.INITIAL and self._postgresql.is_leader():
|
||||
with self._checkpoint_task_lock:
|
||||
if self._checkpoint_task:
|
||||
with self._checkpoint_task:
|
||||
if self._checkpoint_task.result:
|
||||
self._state = REWIND_STATUS.CHECKPOINT
|
||||
if self._checkpoint_task.result is not False:
|
||||
return
|
||||
else:
|
||||
self._checkpoint_task = CriticalTask()
|
||||
return Thread(target=self.__checkpoint, args=(self._checkpoint_task, wakeup)).start()
|
||||
|
||||
if self._postgresql.get_master_timeline() == self._postgresql.pg_control_timeline():
|
||||
self._state = REWIND_STATUS.CHECKPOINT
|
||||
|
||||
def checkpoint_after_promote(self):
|
||||
return self._state == REWIND_STATUS.CHECKPOINT
|
||||
|
||||
def _fetch_missing_wal(self, restore_command, wal_filename):
|
||||
cmd = ''
|
||||
length = len(restore_command)
|
||||
i = 0
|
||||
while i < length:
|
||||
if restore_command[i] == '%' and i + 1 < length:
|
||||
i += 1
|
||||
if restore_command[i] == 'p':
|
||||
cmd += os.path.join(self._postgresql.wal_dir, wal_filename)
|
||||
elif restore_command[i] == 'f':
|
||||
cmd += wal_filename
|
||||
elif restore_command[i] == 'r':
|
||||
cmd += '000000010000000000000001'
|
||||
elif restore_command[i] == '%':
|
||||
cmd += '%'
|
||||
else:
|
||||
cmd += '%'
|
||||
i -= 1
|
||||
else:
|
||||
cmd += restore_command[i]
|
||||
i += 1
|
||||
|
||||
logger.info('Trying to fetch the missing wal: %s', cmd)
|
||||
return self._postgresql.cancellable.call(cmd, shell=True) == 0
|
||||
|
||||
def _find_missing_wal(self, data):
|
||||
# could not open file "$PGDATA/pg_wal/0000000A00006AA100000068": No such file or directory
|
||||
pattern = 'could not open file "'
|
||||
for line in data.decode('utf-8').split('\n'):
|
||||
b = line.find(pattern)
|
||||
if b > -1:
|
||||
b += len(pattern)
|
||||
e = line.find('": ', b)
|
||||
if e > -1:
|
||||
waldir, wal_filename = os.path.split(line[b:e])
|
||||
if waldir.endswith(os.path.sep + 'pg_' + self._postgresql.wal_name) and len(wal_filename) == 24:
|
||||
return wal_filename
|
||||
|
||||
def pg_rewind(self, r):
|
||||
# prepare pg_rewind connection
|
||||
env = self._postgresql.config.write_pgpass(r)
|
||||
env.update(LANG='C', LC_ALL='C', PGOPTIONS='-c statement_timeout=0')
|
||||
dsn = self._postgresql.config.format_dsn(r, True)
|
||||
logger.info('running pg_rewind from %s', dsn)
|
||||
|
||||
restore_command = self._postgresql.config.get('recovery_conf', {}).get('restore_command') \
|
||||
if self._postgresql.major_version < 120000 else self._postgresql.get_guc_value('restore_command')
|
||||
|
||||
cmd = [self._postgresql.pgcommand('pg_rewind')]
|
||||
if self._postgresql.major_version >= 130000 and restore_command:
|
||||
cmd.append('--restore-target-wal')
|
||||
cmd.extend(['-D', self._postgresql.data_dir, '--source-server', dsn])
|
||||
|
||||
while True:
|
||||
results = {}
|
||||
ret = self._postgresql.cancellable.call(cmd, env=env, communicate=results)
|
||||
|
||||
logger.info('pg_rewind exit code=%s', ret)
|
||||
if ret is None:
|
||||
return False
|
||||
|
||||
logger.info(' stdout=%s', results['stdout'].decode('utf-8'))
|
||||
logger.info(' stderr=%s', results['stderr'].decode('utf-8'))
|
||||
if ret == 0:
|
||||
return True
|
||||
|
||||
if not restore_command or self._postgresql.major_version >= 130000:
|
||||
return False
|
||||
|
||||
missing_wal = self._find_missing_wal(results['stderr']) or self._find_missing_wal(results['stdout'])
|
||||
if not missing_wal:
|
||||
return False
|
||||
|
||||
if not self._fetch_missing_wal(restore_command, missing_wal):
|
||||
logger.info('Failed to fetch WAL segment %s required for pg_rewind', missing_wal)
|
||||
return False
|
||||
|
||||
def execute(self, leader):
|
||||
if self._postgresql.is_running() and not self._postgresql.stop(checkpoint=False):
|
||||
return logger.warning('Can not run pg_rewind because postgres is still running')
|
||||
|
||||
# prepare pg_rewind connection
|
||||
r = leader.conn_kwargs(self._postgresql.config.rewind_credentials)
|
||||
|
||||
# 1. make sure that we are really trying to rewind from the master
|
||||
# 2. make sure that pg_control contains the new timeline by:
|
||||
# running a checkpoint or
|
||||
# waiting until Patroni on the master will expose checkpoint_after_promote=True
|
||||
checkpoint_status = leader.checkpoint_after_promote if isinstance(leader, Leader) else None
|
||||
if checkpoint_status is None: # master still runs the old Patroni
|
||||
leader_status = self._postgresql.checkpoint(leader.conn_kwargs(self._postgresql.config.superuser))
|
||||
if leader_status:
|
||||
return logger.warning('Can not use %s for rewind: %s', leader.name, leader_status)
|
||||
elif not checkpoint_status:
|
||||
return logger.info('Waiting for checkpoint on %s before rewind', leader.name)
|
||||
elif not self.check_leader_is_not_in_recovery(**r):
|
||||
return
|
||||
|
||||
if self.pg_rewind(r):
|
||||
self._state = REWIND_STATUS.SUCCESS
|
||||
elif not self.check_leader_is_not_in_recovery(**r):
|
||||
logger.warning('Failed to rewind because master %s become unreachable', leader.name)
|
||||
else:
|
||||
logger.error('Failed to rewind from healty master: %s', leader.name)
|
||||
|
||||
for name in ('remove_data_directory_on_rewind_failure', 'remove_data_directory_on_diverged_timelines'):
|
||||
if self._postgresql.config.get(name):
|
||||
logger.warning('%s is set. removing...', name)
|
||||
self._postgresql.remove_data_directory()
|
||||
self._state = REWIND_STATUS.INITIAL
|
||||
break
|
||||
else:
|
||||
self._state = REWIND_STATUS.FAILED
|
||||
return False
|
||||
|
||||
def reset_state(self):
|
||||
self._state = REWIND_STATUS.INITIAL
|
||||
with self._checkpoint_task_lock:
|
||||
self._checkpoint_task = None
|
||||
|
||||
@property
|
||||
def is_needed(self):
|
||||
return self._state in (REWIND_STATUS.CHECK, REWIND_STATUS.NEED)
|
||||
|
||||
@property
|
||||
def executed(self):
|
||||
return self._state > REWIND_STATUS.NOT_NEED
|
||||
|
||||
@property
|
||||
def failed(self):
|
||||
return self._state == REWIND_STATUS.FAILED
|
||||
|
||||
def read_postmaster_opts(self):
|
||||
"""returns the list of option names/values from postgres.opts, Empty dict if read failed or no file"""
|
||||
result = {}
|
||||
try:
|
||||
with open(os.path.join(self._postgresql.data_dir, 'postmaster.opts')) as f:
|
||||
data = f.read()
|
||||
for opt in data.split('" "'):
|
||||
if '=' in opt and opt.startswith('--'):
|
||||
name, val = opt.split('=', 1)
|
||||
result[name.strip('-')] = val.rstrip('"\n')
|
||||
except IOError:
|
||||
logger.exception('Error when reading postmaster.opts')
|
||||
return result
|
||||
|
||||
def single_user_mode(self, communicate=None, options=None):
|
||||
"""run a given command in a single-user mode. If the command is empty - then just start and stop"""
|
||||
cmd = [self._postgresql.pgcommand('postgres'), '--single', '-D', self._postgresql.data_dir]
|
||||
for opt, val in sorted((options or {}).items()):
|
||||
cmd.extend(['-c', '{0}={1}'.format(opt, val)])
|
||||
# need a database name to connect
|
||||
cmd.append('template1')
|
||||
return self._postgresql.cancellable.call(cmd, communicate=communicate)
|
||||
|
||||
def cleanup_archive_status(self):
|
||||
status_dir = os.path.join(self._postgresql.wal_dir, 'archive_status')
|
||||
try:
|
||||
for f in os.listdir(status_dir):
|
||||
path = os.path.join(status_dir, f)
|
||||
try:
|
||||
if os.path.islink(path):
|
||||
os.unlink(path)
|
||||
elif os.path.isfile(path):
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
logger.exception('Unable to remove %s', path)
|
||||
except OSError:
|
||||
logger.exception('Unable to list %s', status_dir)
|
||||
|
||||
def ensure_clean_shutdown(self):
|
||||
self.cleanup_archive_status()
|
||||
|
||||
# Start in a single user mode and stop to produce a clean shutdown
|
||||
opts = self.read_postmaster_opts()
|
||||
opts.update({'archive_mode': 'on', 'archive_command': 'false'})
|
||||
self._postgresql.config.remove_recovery_conf()
|
||||
return self.single_user_mode(options=opts) == 0 or None
|
||||
@@ -0,0 +1,103 @@
|
||||
import logging
|
||||
|
||||
from patroni.postgresql.connection import get_connection_cursor
|
||||
from collections import defaultdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def compare_slots(s1, s2):
|
||||
return s1['type'] == s2['type'] and (s1['type'] == 'physical' or
|
||||
s1['database'] == s2['database'] and s1['plugin'] == s2['plugin'])
|
||||
|
||||
|
||||
class SlotsHandler(object):
|
||||
|
||||
def __init__(self, postgresql):
|
||||
self._postgresql = postgresql
|
||||
self._replication_slots = {} # already existing replication slots
|
||||
self.schedule()
|
||||
|
||||
def _query(self, sql, *params):
|
||||
return self._postgresql.query(sql, *params, retry=False)
|
||||
|
||||
def load_replication_slots(self):
|
||||
if self._postgresql.major_version >= 90400 and self._schedule_load_slots:
|
||||
replication_slots = {}
|
||||
cursor = self._query('SELECT slot_name, slot_type, plugin, database FROM pg_catalog.pg_replication_slots')
|
||||
for r in cursor:
|
||||
value = {'type': r[1]}
|
||||
if r[1] == 'logical':
|
||||
value.update({'plugin': r[2], 'database': r[3]})
|
||||
replication_slots[r[0]] = value
|
||||
self._replication_slots = replication_slots
|
||||
self._schedule_load_slots = False
|
||||
|
||||
def drop_replication_slot(self, name):
|
||||
cursor = self._query(('SELECT pg_catalog.pg_drop_replication_slot(%s) WHERE EXISTS (SELECT 1 ' +
|
||||
'FROM pg_catalog.pg_replication_slots WHERE slot_name = %s AND NOT active)'), name, name)
|
||||
# In normal situation rowcount should be 1, otherwise either slot doesn't exists or it is still active
|
||||
return cursor.rowcount == 1
|
||||
|
||||
def sync_replication_slots(self, cluster):
|
||||
if self._postgresql.major_version >= 90400:
|
||||
try:
|
||||
self.load_replication_slots()
|
||||
|
||||
slots = cluster.get_replication_slots(self._postgresql.name, self._postgresql.role)
|
||||
|
||||
# drop old replication slots which are not presented in desired slots
|
||||
for name in set(self._replication_slots) - set(slots):
|
||||
if not self.drop_replication_slot(name):
|
||||
logger.error("Failed to drop replication slot '%s'", name)
|
||||
self._schedule_load_slots = True
|
||||
|
||||
immediately_reserve = ', true' if self._postgresql.major_version >= 90600 else ''
|
||||
|
||||
logical_slots = defaultdict(dict)
|
||||
for name, value in slots.items():
|
||||
if name in self._replication_slots and not compare_slots(value, self._replication_slots[name]):
|
||||
logger.info("Trying to drop replication slot '%s' because value is changing from %s to %s",
|
||||
name, self._replication_slots[name], value)
|
||||
if not self.drop_replication_slot(name):
|
||||
logger.error("Failed to drop replication slot '%s'", name)
|
||||
self._schedule_load_slots = True
|
||||
continue
|
||||
self._replication_slots.pop(name)
|
||||
if name not in self._replication_slots:
|
||||
if value['type'] == 'physical':
|
||||
try:
|
||||
self._query(("SELECT pg_catalog.pg_create_physical_replication_slot(%s{0})" +
|
||||
" WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_replication_slots" +
|
||||
" WHERE slot_type = 'physical' AND slot_name = %s)").format(
|
||||
immediately_reserve), name, name)
|
||||
except Exception:
|
||||
logger.exception("Failed to create physical replication slot '%s'", name)
|
||||
self._schedule_load_slots = True
|
||||
elif value['type'] == 'logical' and name not in self._replication_slots:
|
||||
logical_slots[value['database']][name] = value
|
||||
|
||||
# create new logical slots
|
||||
for database, values in logical_slots.items():
|
||||
conn_kwargs = self._postgresql.config.local_connect_kwargs
|
||||
conn_kwargs['database'] = database
|
||||
with get_connection_cursor(**conn_kwargs) as cur:
|
||||
for name, value in values.items():
|
||||
try:
|
||||
cur.execute("SELECT pg_catalog.pg_create_logical_replication_slot(%s, %s)" +
|
||||
" WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_replication_slots" +
|
||||
" WHERE slot_type = 'logical' AND slot_name = %s)",
|
||||
(name, value['plugin'], name))
|
||||
except Exception:
|
||||
logger.exception("Failed to create logical replication slot '%s' plugin='%s'",
|
||||
name, value['plugin'])
|
||||
self._schedule_load_slots = True
|
||||
self._replication_slots = slots
|
||||
except Exception:
|
||||
logger.exception('Exception when changing replication slots')
|
||||
self._schedule_load_slots = True
|
||||
|
||||
def schedule(self, value=None):
|
||||
if value is None:
|
||||
value = self._postgresql.major_version >= 90400
|
||||
self._schedule_load_slots = value
|
||||
@@ -0,0 +1,58 @@
|
||||
import json
|
||||
import urllib3
|
||||
import six
|
||||
|
||||
from six.moves.urllib_parse import urlparse, urlunparse
|
||||
|
||||
from .utils import USER_AGENT
|
||||
|
||||
|
||||
class PatroniRequest(object):
|
||||
|
||||
def __init__(self, config, insecure=False):
|
||||
cert_reqs = 'CERT_NONE' if insecure or config.get('ctl', {}).get('insecure', False) else 'CERT_REQUIRED'
|
||||
self._pool = urllib3.PoolManager(num_pools=10, maxsize=10, cert_reqs=cert_reqs)
|
||||
self.reload_config(config)
|
||||
|
||||
@staticmethod
|
||||
def _get_cfg_value(config, name):
|
||||
return config.get('ctl', {}).get(name) or config.get('restapi', {}).get(name)
|
||||
|
||||
def _apply_pool_param(self, param, value):
|
||||
if value:
|
||||
self._pool.connection_pool_kw[param] = value
|
||||
else:
|
||||
self._pool.connection_pool_kw.pop(param, None)
|
||||
|
||||
def _apply_ssl_file_param(self, config, name):
|
||||
value = self._get_cfg_value(config, name + 'file')
|
||||
self._apply_pool_param(name + '_file', value)
|
||||
return value
|
||||
|
||||
def reload_config(self, config):
|
||||
self._pool.headers = urllib3.make_headers(basic_auth=self._get_cfg_value(config, 'auth'), user_agent=USER_AGENT)
|
||||
|
||||
if self._apply_ssl_file_param(config, 'cert'):
|
||||
self._apply_ssl_file_param(config, 'key')
|
||||
else:
|
||||
self._pool.connection_pool_kw.pop('key_file', None)
|
||||
|
||||
cacert = config.get('ctl', {}).get('cacert') or config.get('restapi', {}).get('cafile')
|
||||
self._apply_pool_param('ca_certs', cacert)
|
||||
|
||||
def request(self, method, url, body=None, **kwargs):
|
||||
if body is not None and not isinstance(body, six.string_types):
|
||||
body = json.dumps(body)
|
||||
return self._pool.request(method.upper(), url, body=body, **kwargs)
|
||||
|
||||
def __call__(self, member, method='GET', endpoint=None, data=None, **kwargs):
|
||||
url = member.api_url
|
||||
if endpoint:
|
||||
scheme, netloc, _, _, _, _ = urlparse(url)
|
||||
url = urlunparse((scheme, netloc, endpoint, '', '', ''))
|
||||
return self.request(method, url, data, **kwargs)
|
||||
|
||||
|
||||
def get(url, verify=True, **kwargs):
|
||||
http = PatroniRequest({}, not verify)
|
||||
return http.request('GET', url, **kwargs)
|
||||
+12
-12
@@ -1,36 +1,36 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import json
|
||||
import logging
|
||||
import requests
|
||||
from requests.exceptions import RequestException
|
||||
import sys
|
||||
import boto.ec2
|
||||
|
||||
from patroni.utils import Retry, RetryFailedError
|
||||
from patroni.request import get as requests_get
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
retry_timeout = 15
|
||||
|
||||
|
||||
class AWSConnection(object):
|
||||
|
||||
def __init__(self, cluster_name):
|
||||
self.available = False
|
||||
self.cluster_name = cluster_name if cluster_name is not None else 'unknown'
|
||||
self._retry = Retry(deadline=retry_timeout, max_delay=5, max_tries=-1, retry_exceptions=(boto.exception,))
|
||||
self._retry = Retry(deadline=300, max_delay=30, max_tries=-1, retry_exceptions=(boto.exception.StandardError,))
|
||||
try:
|
||||
# get the instance id
|
||||
r = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', timeout=0.1)
|
||||
except RequestException:
|
||||
logger.info("cannot query AWS meta-data")
|
||||
r = requests_get('http://169.254.169.254/latest/dynamic/instance-identity/document', timeout=2.1)
|
||||
except Exception:
|
||||
logger.error('cannot query AWS meta-data')
|
||||
return
|
||||
if r.ok:
|
||||
|
||||
if r.status < 400:
|
||||
try:
|
||||
content = r.json()
|
||||
content = json.loads(r.data.decode('utf-8'))
|
||||
self.instance_id = content['instanceId']
|
||||
self.region = content['region']
|
||||
except Exception as e:
|
||||
logger.info('unable to fetch instance id and region from AWS meta-data: {}'.format(e))
|
||||
except Exception:
|
||||
logger.exception('unable to fetch instance id and region from AWS meta-data')
|
||||
return
|
||||
self.available = True
|
||||
|
||||
|
||||
+194
-58
@@ -23,19 +23,29 @@
|
||||
# currently also requires that you configure the restore_command to use wal_e, example:
|
||||
# recovery_conf:
|
||||
# restore_command: envdir /etc/wal-e.d/env wal-e wal-fetch "%f" "%p" -p 1
|
||||
|
||||
from collections import namedtuple
|
||||
import argparse
|
||||
import csv
|
||||
import logging
|
||||
import os
|
||||
import psycopg2
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import argparse
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RETRY_SLEEP_INTERVAL = 1
|
||||
si_prefixes = ['K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
|
||||
|
||||
|
||||
# Meaningful names to the exit codes used by WALERestore
|
||||
ExitCode = type('Enum', (), {
|
||||
'SUCCESS': 0, #: Succeeded
|
||||
'RETRY_LATER': 1, #: External issue, retry later
|
||||
'FAIL': 2 #: Don't try again unless configuration changes
|
||||
})
|
||||
|
||||
|
||||
# We need to know the current PG version in order to figure out the correct WAL directory name
|
||||
@@ -50,66 +60,141 @@ def get_major_version(data_dir):
|
||||
return 0.0
|
||||
|
||||
|
||||
def repr_size(n_bytes):
|
||||
"""
|
||||
>>> repr_size(1000)
|
||||
'1000 Bytes'
|
||||
>>> repr_size(8257332324597)
|
||||
'7.5 TiB'
|
||||
"""
|
||||
if n_bytes < 1024:
|
||||
return '{0} Bytes'.format(n_bytes)
|
||||
i = -1
|
||||
while n_bytes > 1023:
|
||||
n_bytes /= 1024.0
|
||||
i += 1
|
||||
return '{0} {1}iB'.format(round(n_bytes, 1), si_prefixes[i])
|
||||
|
||||
|
||||
def size_as_bytes(size_, prefix):
|
||||
"""
|
||||
>>> size_as_bytes(7.5, 'T')
|
||||
8246337208320
|
||||
"""
|
||||
prefix = prefix.upper()
|
||||
|
||||
assert prefix in si_prefixes
|
||||
|
||||
exponent = si_prefixes.index(prefix) + 1
|
||||
|
||||
return int(size_ * (1024.0 ** exponent))
|
||||
|
||||
|
||||
WALEConfig = namedtuple(
|
||||
'WALEConfig',
|
||||
[
|
||||
'env_dir',
|
||||
'threshold_mb',
|
||||
'threshold_pct',
|
||||
'cmd',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class WALERestore(object):
|
||||
def __init__(self, scope, datadir, connstring, env_dir, threshold_mb, threshold_pct, use_iam, no_master, retries):
|
||||
def __init__(self, scope, datadir, connstring, env_dir, threshold_mb,
|
||||
threshold_pct, use_iam, no_master, retries):
|
||||
self.scope = scope
|
||||
self.master_connection = connstring
|
||||
self.data_dir = datadir
|
||||
self.wal_e = namedtuple('wale', 'dir,threshold_mb,threshold_pct,iam_string,cmd')
|
||||
self.wal_e.dir = env_dir
|
||||
self.wal_e.threshold_mb = threshold_mb
|
||||
self.wal_e.threshold_pct = threshold_pct
|
||||
self.wal_e.iam_string = ' --aws-instance-profile ' if use_iam == 1 else ''
|
||||
self.no_master = no_master
|
||||
self.wal_e.cmd = 'envdir {0} wal-e {1} '.format(self.wal_e.dir, self.wal_e.iam_string)
|
||||
self.init_error = (not os.path.exists(self.wal_e.dir))
|
||||
|
||||
wale_cmd = [
|
||||
'envdir',
|
||||
env_dir,
|
||||
'wal-e',
|
||||
]
|
||||
|
||||
if use_iam == 1:
|
||||
wale_cmd += ['--aws-instance-profile']
|
||||
|
||||
self.wal_e = WALEConfig(
|
||||
env_dir=env_dir,
|
||||
threshold_mb=threshold_mb,
|
||||
threshold_pct=threshold_pct,
|
||||
cmd=wale_cmd,
|
||||
)
|
||||
|
||||
self.init_error = (not os.path.exists(self.wal_e.env_dir))
|
||||
self.retries = retries
|
||||
|
||||
def run(self):
|
||||
""" creates a new replica using WAL-E """
|
||||
if not self.init_error:
|
||||
try:
|
||||
ret = self.should_use_s3_to_create_replica()
|
||||
if ret:
|
||||
return self.create_replica_with_s3()
|
||||
elif ret is None: # caught an exception, need to retry
|
||||
return 1
|
||||
except Exception:
|
||||
logger.exception("Exception when running WAL-E restore")
|
||||
return 2
|
||||
"""
|
||||
Creates a new replica using WAL-E
|
||||
|
||||
Returns
|
||||
-------
|
||||
ExitCode
|
||||
0 = Success
|
||||
1 = Error, try again
|
||||
2 = Error, don't try again
|
||||
|
||||
"""
|
||||
if self.init_error:
|
||||
logger.error('init error: %r did not exist at initialization time',
|
||||
self.wal_e.env_dir)
|
||||
return ExitCode.FAIL
|
||||
|
||||
try:
|
||||
should_use_s3 = self.should_use_s3_to_create_replica()
|
||||
if should_use_s3 is None: # Need to retry
|
||||
return ExitCode.RETRY_LATER
|
||||
elif should_use_s3:
|
||||
return self.create_replica_with_s3()
|
||||
elif not should_use_s3:
|
||||
return ExitCode.FAIL
|
||||
except Exception:
|
||||
logger.exception("Unhandled exception when running WAL-E restore")
|
||||
return ExitCode.FAIL
|
||||
|
||||
def should_use_s3_to_create_replica(self):
|
||||
""" determine whether it makes sense to use S3 and not pg_basebackup """
|
||||
|
||||
threshold_megabytes = self.wal_e.threshold_mb
|
||||
threshold_backup_size_percentage = self.wal_e.threshold_pct
|
||||
threshold_percent = self.wal_e.threshold_pct
|
||||
|
||||
try:
|
||||
latest_backup = subprocess.check_output(self.wal_e.cmd.split() + ['backup-list', '--detail', 'LATEST'])
|
||||
# name last_modified expanded_size_bytes wal_segment_backup_start wal_segment_offset_backup_start
|
||||
# wal_segment_backup_stop wal_segment_offset_backup_stop
|
||||
# base_00000001000000000000007F_00000040 2015-05-18T10:13:25.000Z
|
||||
# 20310671 00000001000000000000007F 00000040
|
||||
# 00000001000000000000007F 00000240
|
||||
backup_strings = latest_backup.decode('utf-8').splitlines() if latest_backup else ()
|
||||
if len(backup_strings) != 2:
|
||||
cmd = self.wal_e.cmd + ['backup-list', '--detail', 'LATEST']
|
||||
|
||||
logger.debug('calling %r', cmd)
|
||||
wale_output = subprocess.check_output(cmd)
|
||||
|
||||
reader = csv.DictReader(wale_output.decode('utf-8').splitlines(),
|
||||
dialect='excel-tab')
|
||||
rows = list(reader)
|
||||
if not len(rows):
|
||||
logger.warning('wal-e did not find any backups')
|
||||
return False
|
||||
|
||||
names = backup_strings[0].split()
|
||||
vals = backup_strings[1].split()
|
||||
if (len(names) != len(vals)) or (len(names) != 7):
|
||||
# This check might not add much, it was performed in the previous
|
||||
# version of this code. since the old version rolled CSV parsing the
|
||||
# check may have been part of the CSV parsing.
|
||||
if len(rows) > 1:
|
||||
logger.warning(
|
||||
'wal-e returned more than one row of backups: %r',
|
||||
rows)
|
||||
return False
|
||||
|
||||
backup_info = dict(zip(names, vals))
|
||||
backup_info = rows[0]
|
||||
except subprocess.CalledProcessError:
|
||||
logger.exception("could not query wal-e latest backup")
|
||||
return None
|
||||
|
||||
try:
|
||||
backup_size = backup_info['expanded_size_bytes']
|
||||
backup_size = int(backup_info['expanded_size_bytes'])
|
||||
backup_start_segment = backup_info['wal_segment_backup_start']
|
||||
backup_start_offset = backup_info['wal_segment_offset_backup_start']
|
||||
except Exception:
|
||||
except KeyError:
|
||||
logger.exception("unable to get some of WALE backup parameters")
|
||||
return None
|
||||
|
||||
@@ -124,24 +209,28 @@ class WALERestore(object):
|
||||
# construct the LSN from the segment and offset
|
||||
backup_start_lsn = '{0}/{1}'.format(lsn_segment, lsn_offset)
|
||||
|
||||
diff_in_bytes = int(backup_size)
|
||||
diff_in_bytes = backup_size
|
||||
attempts_no = 0
|
||||
while True:
|
||||
if self.master_connection:
|
||||
try:
|
||||
# get the difference in bytes between the current WAL location and the backup start offset
|
||||
with psycopg2.connect(self.master_connection) as con:
|
||||
if con.server_version >= 100000:
|
||||
wal_name = 'wal'
|
||||
lsn_name = 'lsn'
|
||||
else:
|
||||
wal_name = 'xlog'
|
||||
lsn_name = 'location'
|
||||
con.autocommit = True
|
||||
with con.cursor() as cur:
|
||||
cur.execute("""SELECT CASE WHEN pg_is_in_recovery()
|
||||
THEN GREATEST(
|
||||
pg_xlog_location_diff(COALESCE(
|
||||
pg_last_xlog_receive_location(), '0/0'), %s)::bigint,
|
||||
pg_xlog_location_diff(
|
||||
pg_last_xlog_replay_location(), %s)::bigint)
|
||||
ELSE pg_xlog_location_diff(
|
||||
pg_current_xlog_location(), %s)::bigint
|
||||
END""", (backup_start_lsn, backup_start_lsn, backup_start_lsn))
|
||||
cur.execute(("SELECT CASE WHEN pg_catalog.pg_is_in_recovery()"
|
||||
" THEN GREATEST(pg_catalog.pg_{0}_{1}_diff(COALESCE("
|
||||
"pg_last_{0}_receive_{1}(), '0/0'), %s)::bigint, "
|
||||
"pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_last_{0}_replay_{1}(), %s)::bigint)"
|
||||
" ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), %s)::bigint"
|
||||
" END").format(wal_name, lsn_name),
|
||||
(backup_start_lsn, backup_start_lsn, backup_start_lsn))
|
||||
|
||||
diff_in_bytes = int(cur.fetchone()[0])
|
||||
except psycopg2.Error:
|
||||
@@ -163,8 +252,47 @@ class WALERestore(object):
|
||||
|
||||
# if the size of the accumulated WAL segments is more than a certan percentage of the backup size
|
||||
# or exceeds the pre-determined size - pg_basebackup is chosen instead.
|
||||
return (diff_in_bytes < int(threshold_megabytes) * 1048576) and\
|
||||
(diff_in_bytes < int(backup_size) * float(threshold_backup_size_percentage) / 100)
|
||||
is_size_thresh_ok = diff_in_bytes < int(threshold_megabytes) * 1048576
|
||||
threshold_pct_bytes = backup_size * threshold_percent / 100.0
|
||||
is_percentage_thresh_ok = float(diff_in_bytes) < int(threshold_pct_bytes)
|
||||
are_thresholds_ok = is_size_thresh_ok and is_percentage_thresh_ok
|
||||
|
||||
class Size(object):
|
||||
def __init__(self, n_bytes, prefix=None):
|
||||
self.n_bytes = n_bytes
|
||||
self.prefix = prefix
|
||||
|
||||
def __repr__(self):
|
||||
if self.prefix is not None:
|
||||
n_bytes = size_as_bytes(self.n_bytes, self.prefix)
|
||||
else:
|
||||
n_bytes = self.n_bytes
|
||||
return repr_size(n_bytes)
|
||||
|
||||
class HumanContext(object):
|
||||
def __init__(self, items):
|
||||
self.items = items
|
||||
|
||||
def __repr__(self):
|
||||
return ', '.join('{}={!r}'.format(key, value)
|
||||
for key, value in self.items)
|
||||
|
||||
human_context = repr(HumanContext([
|
||||
('threshold_size', Size(threshold_megabytes, 'M')),
|
||||
('threshold_percent', threshold_percent),
|
||||
('threshold_percent_size', Size(threshold_pct_bytes)),
|
||||
('backup_size', Size(backup_size)),
|
||||
('backup_diff', Size(diff_in_bytes)),
|
||||
('is_size_thresh_ok', is_size_thresh_ok),
|
||||
('is_percentage_thresh_ok', is_percentage_thresh_ok),
|
||||
]))
|
||||
|
||||
if not are_thresholds_ok:
|
||||
logger.info('wal-e backup size diff is over threshold, falling back '
|
||||
'to other means of restore: %s', human_context)
|
||||
else:
|
||||
logger.info('Thresholds are OK, using wal-e basebackup: %s', human_context)
|
||||
return are_thresholds_ok
|
||||
|
||||
def fix_subdirectory_path_if_broken(self, dirname):
|
||||
# in case it is a symlink pointing to a non-existing location, remove it and create the actual directory
|
||||
@@ -187,15 +315,19 @@ class WALERestore(object):
|
||||
def create_replica_with_s3(self):
|
||||
# if we're set up, restore the replica using fetch latest
|
||||
try:
|
||||
ret = subprocess.call(self.wal_e.cmd.split() + ['backup-fetch', '{}'.format(self.data_dir), 'LATEST'])
|
||||
cmd = self.wal_e.cmd + ['backup-fetch',
|
||||
'{}'.format(self.data_dir),
|
||||
'LATEST']
|
||||
logger.debug('calling: %r', cmd)
|
||||
exit_code = subprocess.call(cmd)
|
||||
except Exception as e:
|
||||
logger.error('Error when fetching backup with WAL-E: {0}'.format(e))
|
||||
return 1
|
||||
return ExitCode.RETRY_LATER
|
||||
|
||||
if (ret == 0 and not
|
||||
self.fix_subdirectory_path_if_broken('pg_xlog' if get_major_version(self.data_dir) < 10.0 else 'pg_wal')):
|
||||
return 2
|
||||
return ret
|
||||
if (exit_code == 0 and not
|
||||
self.fix_subdirectory_path_if_broken('pg_xlog' if get_major_version(self.data_dir) < 10 else 'pg_wal')):
|
||||
return ExitCode.FAIL
|
||||
return exit_code
|
||||
|
||||
|
||||
def main():
|
||||
@@ -213,6 +345,9 @@ def main():
|
||||
parser.add_argument('--no_master', type=int, default=0)
|
||||
args = parser.parse_args()
|
||||
|
||||
exit_code = None
|
||||
assert args.retries >= 0
|
||||
|
||||
# Retry cloning in a loop. We do separate retries for the master
|
||||
# connection attempt inside should_use_s3_to_create_replica,
|
||||
# because we need to differentiate between the last attempt and
|
||||
@@ -223,12 +358,13 @@ def main():
|
||||
env_dir=args.envdir, threshold_mb=args.threshold_megabytes,
|
||||
threshold_pct=args.threshold_backup_size_percentage, use_iam=args.use_iam,
|
||||
no_master=args.no_master, retries=args.retries)
|
||||
ret = restore.run()
|
||||
if ret != 1: # only WAL-E failures lead to the retry
|
||||
exit_code = restore.run()
|
||||
if not exit_code == ExitCode.RETRY_LATER: # only WAL-E failures lead to the retry
|
||||
logger.debug('exit_code is %r, not retrying', exit_code)
|
||||
break
|
||||
time.sleep(RETRY_SLEEP_INTERVAL)
|
||||
|
||||
return ret
|
||||
return exit_code
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+244
-71
@@ -1,12 +1,26 @@
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import time
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from dateutil import tz
|
||||
from patroni.exceptions import PatroniException
|
||||
|
||||
from .exceptions import PatroniException
|
||||
from .version import __version__
|
||||
|
||||
tzutc = tz.tzutc()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
USER_AGENT = 'Patroni/{0} Python/{1} {2}'.format(__version__, platform.python_version(), platform.system())
|
||||
OCT_RE = re.compile(r'^[-+]?0[0-7]*')
|
||||
DEC_RE = re.compile(r'^[-+]?(0|[1-9][0-9]*)')
|
||||
HEX_RE = re.compile(r'^[-+]?0x[0-9a-fA-F]+')
|
||||
DBL_RE = re.compile(r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?')
|
||||
|
||||
|
||||
def deep_compare(obj1, obj2):
|
||||
"""
|
||||
@@ -89,42 +103,77 @@ def strtol(value, strict=True):
|
||||
True
|
||||
>>> strtol(' d ') == (None, 'd')
|
||||
True
|
||||
>>> strtol(' 1 d ') == (1, ' d')
|
||||
True
|
||||
>>> strtol('9s', False) == (9, 's')
|
||||
True
|
||||
>>> strtol(' s ', False) == (1, 's')
|
||||
True
|
||||
"""
|
||||
value = str(value).strip()
|
||||
l = len(value)
|
||||
i = 0
|
||||
# skip sign:
|
||||
if i < l and value[i] in ('-', '+'):
|
||||
i += 1
|
||||
for regex, base in ((HEX_RE, 16), (OCT_RE, 8), (DEC_RE, 10)):
|
||||
match = regex.match(value)
|
||||
if match:
|
||||
end = match.end()
|
||||
return int(value[:end], base), value[end:]
|
||||
return (None if strict else 1), value
|
||||
|
||||
# we always expect to get digit in the beginning
|
||||
if i < l and value[i].isdigit():
|
||||
if value[i] == '0':
|
||||
i += 1
|
||||
if i < l and value[i] in ('x', 'X'): # '0' followed by 'x': HEX
|
||||
base = 16
|
||||
i += 1
|
||||
else: # just starts with '0': OCT
|
||||
base = 8
|
||||
else: # any other digit: DEC
|
||||
base = 10
|
||||
|
||||
ret = None
|
||||
while i <= l:
|
||||
try: # try to find maximally long number
|
||||
i += 1 # by giving to `int` longer and longer strings
|
||||
ret = int(value[:i], base)
|
||||
except ValueError: # until we will not get an exception or end of the string
|
||||
i -= 1
|
||||
break
|
||||
if ret is not None: # yay! there is a number in the beginning of the string
|
||||
return ret, value[i:].strip() # return the number and the "rest"
|
||||
def strtod(value):
|
||||
"""As most as possible close equivalent of strtod(3) function used by postgres to parse parameter values.
|
||||
>>> strtod(' A ') == (None, 'A')
|
||||
True
|
||||
"""
|
||||
value = str(value).strip()
|
||||
match = DBL_RE.match(value)
|
||||
if match:
|
||||
end = match.end()
|
||||
return float(value[:end]), value[end:]
|
||||
return None, value
|
||||
|
||||
return (None if strict else 1), value.strip()
|
||||
|
||||
def rint(value):
|
||||
"""
|
||||
>>> rint(0.5) == 0
|
||||
True
|
||||
>>> rint(0.501) == 1
|
||||
True
|
||||
>>> rint(1.5) == 2
|
||||
True
|
||||
"""
|
||||
|
||||
ret = round(value)
|
||||
return 2.0 * round(value / 2.0) if abs(ret - value) == 0.5 else ret
|
||||
|
||||
|
||||
def convert_to_base_unit(value, unit, base_unit):
|
||||
convert = {
|
||||
'B': {'B': 1, 'kB': 1024, 'MB': 1024 * 1024, 'GB': 1024 * 1024 * 1024, 'TB': 1024 * 1024 * 1024 * 1024},
|
||||
'kB': {'B': 1.0 / 1024, 'kB': 1, 'MB': 1024, 'GB': 1024 * 1024, 'TB': 1024 * 1024 * 1024},
|
||||
'MB': {'B': 1.0 / (1024 * 1024), 'kB': 1.0 / 1024, 'MB': 1, 'GB': 1024, 'TB': 1024 * 1024},
|
||||
'ms': {'us': 1.0 / 1000, 'ms': 1, 's': 1000, 'min': 1000 * 60, 'h': 1000 * 60 * 60, 'd': 1000 * 60 * 60 * 24},
|
||||
's': {'us': 1.0 / (1000 * 1000), 'ms': 1.0 / 1000, 's': 1, 'min': 60, 'h': 60 * 60, 'd': 60 * 60 * 24},
|
||||
'min': {'us': 1.0 / (1000 * 1000 * 60), 'ms': 1.0 / (1000 * 60), 's': 1.0 / 60, 'min': 1, 'h': 60, 'd': 60 * 24}
|
||||
}
|
||||
|
||||
round_order = {
|
||||
'TB': 'GB', 'GB': 'MB', 'MB': 'kB', 'kB': 'B',
|
||||
'd': 'h', 'h': 'min', 'min': 's', 's': 'ms', 'ms': 'us'
|
||||
}
|
||||
|
||||
if base_unit and base_unit not in convert:
|
||||
base_value, base_unit = strtol(base_unit, False)
|
||||
else:
|
||||
base_value = 1
|
||||
|
||||
if base_unit in convert and unit in convert[base_unit]:
|
||||
value *= convert[base_unit][unit] / float(base_value)
|
||||
|
||||
if unit in round_order:
|
||||
multiplier = convert[base_unit][round_order[unit]]
|
||||
value = rint(value / float(multiplier)) * multiplier
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def parse_int(value, base_unit=None):
|
||||
@@ -137,56 +186,71 @@ def parse_int(value, base_unit=None):
|
||||
True
|
||||
>>> parse_int('1000 ms', 's') == 1
|
||||
True
|
||||
>>> parse_int('1GB', 'MB') is None
|
||||
>>> parse_int('1TB', 'GB') is None
|
||||
True
|
||||
>>> parse_int(0) == 0
|
||||
True
|
||||
>>> parse_int('6GB', '16MB') == 384
|
||||
True
|
||||
>>> parse_int('4097.4kB', 'kB') == 4097
|
||||
True
|
||||
>>> parse_int('4097.5kB', 'kB') == 4098
|
||||
True
|
||||
"""
|
||||
|
||||
convert = {
|
||||
'kB': {'kB': 1, 'MB': 1024, 'GB': 1024 * 1024, 'TB': 1024 * 1024 * 1024},
|
||||
'ms': {'ms': 1, 's': 1000, 'min': 1000 * 60, 'h': 1000 * 60 * 60, 'd': 1000 * 60 * 60 * 24},
|
||||
's': {'ms': -1000, 's': 1, 'min': 60, 'h': 60 * 60, 'd': 60 * 60 * 24},
|
||||
'min': {'ms': -1000 * 60, 's': -60, 'min': 1, 'h': 60, 'd': 60 * 24}
|
||||
}
|
||||
val, unit = strtol(value)
|
||||
if val is None and unit.startswith('.') or unit and unit[0] in ('.', 'e', 'E'):
|
||||
val, unit = strtod(value)
|
||||
|
||||
value, unit = strtol(value)
|
||||
if value is not None:
|
||||
if val is not None:
|
||||
unit = unit.strip()
|
||||
if not unit:
|
||||
return value
|
||||
return int(rint(val))
|
||||
|
||||
if base_unit and base_unit not in convert:
|
||||
base_value, base_unit = strtol(base_unit, False)
|
||||
else:
|
||||
base_value = 1
|
||||
if base_unit in convert and unit in convert[base_unit]:
|
||||
multiplier = convert[base_unit][unit]
|
||||
if multiplier < 0:
|
||||
value /= -multiplier
|
||||
else:
|
||||
value *= multiplier
|
||||
return int(value/base_value)
|
||||
val = convert_to_base_unit(val, unit, base_unit)
|
||||
if val is not None:
|
||||
return int(rint(val))
|
||||
|
||||
|
||||
def parse_real(value, base_unit=None):
|
||||
"""
|
||||
>>> parse_real(' +0.0005 ') == 0.0005
|
||||
True
|
||||
>>> parse_real('0.0005ms', 'ms') == 0.0
|
||||
True
|
||||
>>> parse_real('0.00051ms', 'ms') == 0.001
|
||||
True
|
||||
"""
|
||||
val, unit = strtod(value)
|
||||
|
||||
if val is not None:
|
||||
unit = unit.strip()
|
||||
if not unit:
|
||||
return val
|
||||
|
||||
return convert_to_base_unit(val, unit, base_unit)
|
||||
|
||||
|
||||
def compare_values(vartype, unit, old_value, new_value):
|
||||
"""
|
||||
>>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE')
|
||||
True
|
||||
>>> compare_values('real', None, '1.23', 1.23)
|
||||
>>> compare_values('real', None, '1e-06', 0.000001)
|
||||
True
|
||||
"""
|
||||
|
||||
# if the integer or bool new_value is not correct this function will return False
|
||||
if vartype == 'bool':
|
||||
old_value = parse_bool(old_value)
|
||||
new_value = parse_bool(new_value)
|
||||
elif vartype == 'integer':
|
||||
old_value = parse_int(old_value)
|
||||
new_value = parse_int(new_value, unit)
|
||||
elif vartype == 'enum':
|
||||
return str(old_value).lower() == str(new_value).lower()
|
||||
else: # ('string', 'real')
|
||||
return str(old_value) == str(new_value)
|
||||
converters = {
|
||||
'bool': lambda v1, v2: parse_bool(v1),
|
||||
'integer': parse_int,
|
||||
'real': parse_real,
|
||||
'enum': lambda v1, v2: str(v1).lower(),
|
||||
'string': lambda v1, v2: str(v1)
|
||||
}
|
||||
|
||||
convert = converters.get(vartype) or converters['string']
|
||||
old_value = convert(old_value, None)
|
||||
new_value = convert(new_value, unit)
|
||||
|
||||
return old_value is not None and new_value is not None and old_value == new_value
|
||||
|
||||
|
||||
@@ -194,10 +258,6 @@ def _sleep(interval):
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
def is_valid_pg_version(version):
|
||||
return re.match(r'[1-9][0-9]?(\.(0|([1-9][0-9]?))){2}$', version)
|
||||
|
||||
|
||||
class RetryFailedError(PatroniException):
|
||||
|
||||
"""Raised when retrying an operation ultimately failed, after retrying the maximum number of attempts."""
|
||||
@@ -242,6 +302,17 @@ class Retry(object):
|
||||
max_jitter=self.max_jitter / 100.0, max_delay=self.max_delay, sleep_func=self.sleep_func,
|
||||
deadline=self.deadline, retry_exceptions=self.retry_exceptions)
|
||||
|
||||
@property
|
||||
def sleeptime(self):
|
||||
return self._cur_delay + (random.randint(0, self.max_jitter) / 100.0)
|
||||
|
||||
def update_delay(self):
|
||||
self._cur_delay = min(self._cur_delay * self.backoff, self.max_delay)
|
||||
|
||||
@property
|
||||
def stoptime(self):
|
||||
return self._cur_stoptime
|
||||
|
||||
def __call__(self, func, *args, **kwargs):
|
||||
"""Call a function with arguments until it completes without throwing a `retry_exceptions`
|
||||
|
||||
@@ -257,18 +328,20 @@ class Retry(object):
|
||||
if self.deadline is not None and self._cur_stoptime is None:
|
||||
self._cur_stoptime = time.time() + self.deadline
|
||||
return func(*args, **kwargs)
|
||||
except self.retry_exceptions:
|
||||
except self.retry_exceptions as e:
|
||||
# Note: max_tries == -1 means infinite tries.
|
||||
if self._attempts == self.max_tries:
|
||||
logger.warning('Retry got exception: %s', e)
|
||||
raise RetryFailedError("Too many retry attempts")
|
||||
self._attempts += 1
|
||||
sleeptime = self._cur_delay + (random.randint(0, self.max_jitter) / 100.0)
|
||||
sleeptime = hasattr(e, 'sleeptime') and e.sleeptime or self.sleeptime
|
||||
|
||||
if self._cur_stoptime is not None and time.time() + sleeptime >= self._cur_stoptime:
|
||||
logger.warning('Retry got exception: %s', e)
|
||||
raise RetryFailedError("Exceeded retry deadline")
|
||||
else:
|
||||
self.sleep_func(sleeptime)
|
||||
self._cur_delay = min(self._cur_delay * self.backoff, self.max_delay)
|
||||
logger.debug('Retry got exception: %s', e)
|
||||
self.sleep_func(sleeptime)
|
||||
self.update_delay()
|
||||
|
||||
|
||||
def polling_loop(timeout, interval=1):
|
||||
@@ -280,3 +353,103 @@ def polling_loop(timeout, interval=1):
|
||||
yield iteration
|
||||
iteration += 1
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
def split_host_port(value, default_port):
|
||||
t = value.rsplit(':', 1)
|
||||
if ':' in t[0]:
|
||||
t[0] = t[0].strip('[]')
|
||||
t.append(default_port)
|
||||
return t[0], int(t[1])
|
||||
|
||||
|
||||
def uri(proto, netloc, path='', user=None):
|
||||
host, port = netloc if isinstance(netloc, (list, tuple)) else split_host_port(netloc, 0)
|
||||
if host and ':' in host and host[0] != '[' and host[-1] != ']':
|
||||
host = '[{0}]'.format(host)
|
||||
port = ':{0}'.format(port) if port else ''
|
||||
path = '/{0}'.format(path) if path and not path.startswith('/') else path
|
||||
user = '{0}@'.format(user) if user else ''
|
||||
return '{0}://{1}{2}{3}{4}'.format(proto, user, host, port, path)
|
||||
|
||||
|
||||
def is_standby_cluster(config):
|
||||
# Check whether or not provided configuration describes a standby cluster
|
||||
return isinstance(config, dict) and (config.get('host') or config.get('port') or config.get('restore_command'))
|
||||
|
||||
|
||||
def cluster_as_json(cluster):
|
||||
leader_name = cluster.leader.name if cluster.leader else None
|
||||
xlog_location_cluster = cluster.last_leader_operation or 0
|
||||
|
||||
ret = {'members': []}
|
||||
for m in cluster.members:
|
||||
if m.name == leader_name:
|
||||
config = cluster.config.data if cluster.config and cluster.config.modify_index else {}
|
||||
role = 'standby_leader' if is_standby_cluster(config.get('standby_cluster')) else 'leader'
|
||||
elif m.name == cluster.sync.sync_standby:
|
||||
role = 'sync_standby'
|
||||
else:
|
||||
role = 'replica'
|
||||
|
||||
member = {'name': m.name, 'role': role, 'state': m.data.get('state', ''), 'api_url': m.api_url}
|
||||
conn_kwargs = m.conn_kwargs()
|
||||
if conn_kwargs.get('host'):
|
||||
member['host'] = conn_kwargs['host']
|
||||
if conn_kwargs.get('port'):
|
||||
member['port'] = int(conn_kwargs['port'])
|
||||
optional_attributes = ('timeline', 'pending_restart', 'scheduled_restart', 'tags')
|
||||
member.update({n: m.data[n] for n in optional_attributes if n in m.data})
|
||||
|
||||
if m.name != leader_name:
|
||||
xlog_location = m.data.get('xlog_location')
|
||||
if xlog_location is None:
|
||||
member['lag'] = 'unknown'
|
||||
elif xlog_location_cluster >= xlog_location:
|
||||
member['lag'] = xlog_location_cluster - xlog_location
|
||||
else:
|
||||
member['lag'] = 0
|
||||
|
||||
ret['members'].append(member)
|
||||
|
||||
# sort members by name for consistency
|
||||
ret['members'].sort(key=lambda m: m['name'])
|
||||
if cluster.is_paused():
|
||||
ret['pause'] = True
|
||||
if cluster.failover and cluster.failover.scheduled_at:
|
||||
ret['scheduled_switchover'] = {'at': cluster.failover.scheduled_at.isoformat()}
|
||||
if cluster.failover.leader:
|
||||
ret['scheduled_switchover']['from'] = cluster.failover.leader
|
||||
if cluster.failover.candidate:
|
||||
ret['scheduled_switchover']['to'] = cluster.failover.candidate
|
||||
return ret
|
||||
|
||||
|
||||
def is_subpath(d1, d2):
|
||||
real_d1 = os.path.realpath(d1) + os.path.sep
|
||||
real_d2 = os.path.realpath(os.path.join(real_d1, d2))
|
||||
return os.path.commonprefix([real_d1, real_d2 + os.path.sep]) == real_d1
|
||||
|
||||
|
||||
def validate_directory(d, msg="{} {}"):
|
||||
if not os.path.exists(d):
|
||||
try:
|
||||
os.makedirs(d)
|
||||
except OSError as e:
|
||||
logger.error(e)
|
||||
raise PatroniException(msg.format(d, "couldn't create the directory"))
|
||||
elif os.path.isdir(d):
|
||||
try:
|
||||
fd, tmpfile = tempfile.mkstemp(dir=d)
|
||||
os.close(fd)
|
||||
os.remove(tmpfile)
|
||||
except OSError:
|
||||
raise PatroniException(msg.format(d, "the directory is not writable"))
|
||||
else:
|
||||
raise PatroniException(msg.format(d, "is not a directory"))
|
||||
|
||||
|
||||
def data_directory_is_empty(data_dir):
|
||||
if not os.path.exists(data_dir):
|
||||
return True
|
||||
return all(os.name != 'nt' and (n.startswith('.') or n == 'lost+found') for n in os.listdir(data_dir))
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import socket
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from patroni.utils import split_host_port, data_directory_is_empty
|
||||
from patroni.ctl import find_executable
|
||||
from patroni.dcs import dcs_modules
|
||||
from patroni.exceptions import ConfigParseError
|
||||
from six import string_types
|
||||
|
||||
|
||||
def data_directory_empty(data_dir):
|
||||
if os.path.isfile(os.path.join(data_dir, "global", "pg_control")):
|
||||
return False
|
||||
return data_directory_is_empty(data_dir)
|
||||
|
||||
|
||||
def validate_connect_address(address):
|
||||
try:
|
||||
host, _ = split_host_port(address, 1)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
raise ConfigParseError("contains a wrong value")
|
||||
if host in ["127.0.0.1", "0.0.0.0", "*", "::1", "localhost"]:
|
||||
raise ConfigParseError('must not contain "127.0.0.1", "0.0.0.0", "*", "::1", "localhost"')
|
||||
return True
|
||||
|
||||
|
||||
def validate_host_port(host_port, listen=False, multiple_hosts=False):
|
||||
try:
|
||||
hosts, port = split_host_port(host_port, None)
|
||||
except (ValueError, TypeError):
|
||||
raise ConfigParseError("contains a wrong value")
|
||||
else:
|
||||
if multiple_hosts:
|
||||
hosts = hosts.split(",")
|
||||
else:
|
||||
hosts = [hosts]
|
||||
for host in hosts:
|
||||
proto = socket.getaddrinfo(host, "", 0, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
|
||||
s = socket.socket(proto[0][0], socket.SOCK_STREAM)
|
||||
try:
|
||||
if s.connect_ex((host, port)) == 0:
|
||||
if listen:
|
||||
raise ConfigParseError("Port {} is already in use.".format(port))
|
||||
elif not listen:
|
||||
raise ConfigParseError("{} is not reachable".format(host_port))
|
||||
except socket.gaierror as e:
|
||||
raise ConfigParseError(e)
|
||||
finally:
|
||||
s.close()
|
||||
return True
|
||||
|
||||
|
||||
def comma_separated_host_port(string):
|
||||
assert all([validate_host_port(s.strip()) for s in string.split(",")]), "didn't pass the validation"
|
||||
return True
|
||||
|
||||
|
||||
def validate_host_port_listen(host_port):
|
||||
return validate_host_port(host_port, listen=True)
|
||||
|
||||
|
||||
def validate_host_port_listen_multiple_hosts(host_port):
|
||||
return validate_host_port(host_port, listen=True, multiple_hosts=True)
|
||||
|
||||
|
||||
def is_ipv4_address(ip):
|
||||
try:
|
||||
socket.inet_aton(ip)
|
||||
except Exception:
|
||||
raise ConfigParseError("Is not a valid ipv4 address")
|
||||
return True
|
||||
|
||||
|
||||
def is_ipv6_address(ip):
|
||||
try:
|
||||
socket.inet_pton(socket.AF_INET6, ip)
|
||||
except Exception:
|
||||
raise ConfigParseError("Is not a valid ipv6 address")
|
||||
return True
|
||||
|
||||
|
||||
def get_major_version(bin_dir=None):
|
||||
if not bin_dir:
|
||||
binary = 'postgres'
|
||||
else:
|
||||
binary = os.path.join(bin_dir, 'postgres')
|
||||
version = subprocess.check_output([binary, '--version']).decode()
|
||||
version = re.match(r'^[^\s]+ [^\s]+ (\d+)(\.(\d+))?', version)
|
||||
return '.'.join([version.group(1), version.group(3)]) if int(version.group(1)) < 10 else version.group(1)
|
||||
|
||||
|
||||
def validate_data_dir(data_dir):
|
||||
if not data_dir:
|
||||
raise ConfigParseError("is an empty string")
|
||||
elif os.path.exists(data_dir) and not os.path.isdir(data_dir):
|
||||
raise ConfigParseError("is not a directory")
|
||||
elif not data_directory_empty(data_dir):
|
||||
if not os.path.exists(os.path.join(data_dir, "PG_VERSION")):
|
||||
raise ConfigParseError("doesn't look like a valid data directory")
|
||||
else:
|
||||
with open(os.path.join(data_dir, "PG_VERSION"), "r") as version:
|
||||
pgversion = version.read().strip()
|
||||
waldir = ("pg_wal" if float(pgversion) >= 10 else "pg_xlog")
|
||||
if not os.path.isdir(os.path.join(data_dir, waldir)):
|
||||
raise ConfigParseError("data dir for the cluster is not empty, but doesn't contain"
|
||||
" \"{}\" directory".format(waldir))
|
||||
bin_dir = schema.data.get("postgresql", {}).get("bin_dir", None)
|
||||
major_version = get_major_version(bin_dir)
|
||||
if pgversion != major_version:
|
||||
raise ConfigParseError("data_dir directory postgresql version ({}) doesn't match with "
|
||||
"'postgres --version' output ({})".format(pgversion, major_version))
|
||||
return True
|
||||
|
||||
|
||||
class Result(object):
|
||||
def __init__(self, status, error="didn't pass validation", level=0, path="", data=""):
|
||||
self.status = status
|
||||
self.path = path
|
||||
self.data = data
|
||||
self.level = level
|
||||
self._error = error
|
||||
if not self.status:
|
||||
self.error = error
|
||||
else:
|
||||
self.error = None
|
||||
|
||||
def __repr__(self):
|
||||
return self.path + (" " + str(self.data) + " " + self._error if self.error else "")
|
||||
|
||||
|
||||
class Case(object):
|
||||
def __init__(self, schema):
|
||||
self._schema = schema
|
||||
|
||||
|
||||
class Or(object):
|
||||
def __init__(self, *args):
|
||||
self.args = args
|
||||
|
||||
|
||||
class Optional(object):
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
|
||||
class Directory(object):
|
||||
def __init__(self, contains=None, contains_executable=None):
|
||||
self.contains = contains
|
||||
self.contains_executable = contains_executable
|
||||
|
||||
def validate(self, name):
|
||||
if not name:
|
||||
yield Result(False, "is an empty string")
|
||||
elif not os.path.exists(name):
|
||||
yield Result(False, "Directory '{}' does not exist.".format(name))
|
||||
elif not os.path.isdir(name):
|
||||
yield Result(False, "'{}' is not a directory.".format(name))
|
||||
else:
|
||||
if self.contains:
|
||||
for path in self.contains:
|
||||
if not os.path.exists(os.path.join(name, path)):
|
||||
yield Result(False, "'{}' does not contain '{}'".format(name, path))
|
||||
if self.contains_executable:
|
||||
for program in self.contains_executable:
|
||||
if not find_executable(program, name):
|
||||
yield Result(False, "'{}' does not contain '{}'".format(name, program))
|
||||
|
||||
|
||||
class Schema(object):
|
||||
def __init__(self, validator):
|
||||
self.validator = validator
|
||||
|
||||
def __call__(self, data):
|
||||
for i in self.validate(data):
|
||||
if not i.status:
|
||||
print(i)
|
||||
|
||||
def validate(self, data):
|
||||
self.data = data
|
||||
if isinstance(self.validator, string_types):
|
||||
yield Result(isinstance(self.data, string_types), "is not a string", level=1, data=self.data)
|
||||
elif issubclass(type(self.validator), type):
|
||||
validator = self.validator
|
||||
if self.validator == str:
|
||||
validator = string_types
|
||||
yield Result(isinstance(self.data, validator),
|
||||
"is not {}".format(_get_type_name(self.validator)), level=1, data=self.data)
|
||||
elif callable(self.validator):
|
||||
if hasattr(self.validator, "expected_type"):
|
||||
if not isinstance(data, self.validator.expected_type):
|
||||
yield Result(False, "is not {}"
|
||||
.format(_get_type_name(self.validator.expected_type)), level=1, data=self.data)
|
||||
return
|
||||
try:
|
||||
self.validator(data)
|
||||
yield Result(True, data=self.data)
|
||||
except Exception as e:
|
||||
yield Result(False, "didn't pass validation: {}".format(e), data=self.data)
|
||||
elif isinstance(self.validator, dict):
|
||||
if not len(self.validator):
|
||||
yield Result(isinstance(self.data, dict), "is not a dictionary", level=1, data=self.data)
|
||||
elif isinstance(self.validator, list):
|
||||
if not isinstance(self.data, list):
|
||||
yield Result(isinstance(self.data, list), "is not a list", level=1, data=self.data)
|
||||
return
|
||||
for i in self.iter():
|
||||
yield i
|
||||
|
||||
def iter(self):
|
||||
if isinstance(self.validator, dict):
|
||||
if not isinstance(self.data, dict):
|
||||
yield Result(False, "is not a dictionary.", level=1)
|
||||
else:
|
||||
for i in self.iter_dict():
|
||||
yield i
|
||||
elif isinstance(self.validator, list):
|
||||
if len(self.data) == 0:
|
||||
yield Result(False, "is an empty list", data=self.data)
|
||||
if len(self.validator) > 0:
|
||||
for key, value in enumerate(self.data):
|
||||
for v in Schema(self.validator[0]).validate(value):
|
||||
yield Result(v.status, v.error,
|
||||
path=(str(key) + ("." + v.path if v.path else "")), level=v.level, data=value)
|
||||
elif isinstance(self.validator, Directory):
|
||||
for v in self.validator.validate(self.data):
|
||||
yield v
|
||||
elif isinstance(self.validator, Or):
|
||||
for i in self.iter_or():
|
||||
yield i
|
||||
|
||||
def iter_dict(self):
|
||||
for key in self.validator.keys():
|
||||
for d in self._data_key(key):
|
||||
if d not in self.data and not isinstance(key, Optional):
|
||||
yield Result(False, "is not defined.", path=d)
|
||||
elif d not in self.data and isinstance(key, Optional):
|
||||
continue
|
||||
else:
|
||||
validator = self.validator[key]
|
||||
if isinstance(key, Or) and isinstance(self.validator[key], Case):
|
||||
validator = self.validator[key]._schema[d]
|
||||
for v in Schema(validator).validate(self.data[d]):
|
||||
yield Result(v.status, v.error,
|
||||
path=(d + ("." + v.path if v.path else "")), level=v.level, data=v.data)
|
||||
|
||||
def iter_or(self):
|
||||
results = []
|
||||
for a in self.validator.args:
|
||||
r = []
|
||||
for v in Schema(a).validate(self.data):
|
||||
r.append(v)
|
||||
if any([x.status for x in r]) and not all([x.status for x in r]):
|
||||
results += filter(lambda x: not x.status, r)
|
||||
else:
|
||||
results += r
|
||||
if not any([x.status for x in results]):
|
||||
max_level = 3
|
||||
for v in sorted(results, key=lambda x: x.level):
|
||||
if v.level > max_level:
|
||||
break
|
||||
max_level = v.level
|
||||
yield Result(v.status, v.error, path=v.path, level=v.level, data=v.data)
|
||||
|
||||
def _data_key(self, key):
|
||||
if isinstance(self.data, dict) and isinstance(key, str):
|
||||
yield key
|
||||
elif isinstance(key, Optional):
|
||||
yield key.name
|
||||
elif isinstance(key, Or):
|
||||
if any([i in self.data for i in key.args]):
|
||||
for i in key.args:
|
||||
if i in self.data:
|
||||
yield i
|
||||
else:
|
||||
for i in key.args:
|
||||
yield i
|
||||
|
||||
|
||||
def _get_type_name(python_type):
|
||||
return {str: 'a string', int: 'and integer', float: 'a number', bool: 'a boolean',
|
||||
list: 'an array', dict: 'a dictionary', string_types: "a string"}.get(
|
||||
python_type, getattr(python_type, __name__, "unknown type"))
|
||||
|
||||
|
||||
def assert_(condition, message="Wrong value"):
|
||||
assert condition, message
|
||||
|
||||
|
||||
userattributes = {"username": "", Optional("password"): ""}
|
||||
available_dcs = [m.split(".")[-1] for m in dcs_modules()]
|
||||
comma_separated_host_port.expected_type = string_types
|
||||
validate_connect_address.expected_type = string_types
|
||||
validate_host_port_listen.expected_type = string_types
|
||||
validate_host_port_listen_multiple_hosts.expected_type = string_types
|
||||
validate_data_dir.expected_type = string_types
|
||||
|
||||
schema = Schema({
|
||||
"name": str,
|
||||
"scope": str,
|
||||
"restapi": {
|
||||
"listen": validate_host_port_listen,
|
||||
"connect_address": validate_connect_address
|
||||
},
|
||||
Optional("bootstrap"): {
|
||||
"dcs": {
|
||||
Optional("ttl"): int,
|
||||
Optional("loop_wait"): int,
|
||||
Optional("retry_timeout"): int,
|
||||
Optional("maximum_lag_on_failover"): int
|
||||
},
|
||||
"pg_hba": [str],
|
||||
"initdb": [Or(str, dict)]
|
||||
},
|
||||
Or(*available_dcs): Case({
|
||||
"consul": {
|
||||
Or("host", "url"): Case({
|
||||
"host": validate_host_port,
|
||||
"url": str})
|
||||
},
|
||||
"etcd": {
|
||||
Or("host", "hosts", "srv", "url", "proxy"): Case({
|
||||
"host": validate_host_port,
|
||||
"hosts": Or(comma_separated_host_port, [validate_host_port]),
|
||||
"srv": str,
|
||||
"url": str,
|
||||
"proxy": str})
|
||||
},
|
||||
"exhibitor": {
|
||||
"hosts": [str],
|
||||
"port": lambda i: assert_(int(i) <= 65535),
|
||||
Optional("pool_interval"): int
|
||||
},
|
||||
"zookeeper": {
|
||||
"hosts": Or(comma_separated_host_port, [validate_host_port]),
|
||||
},
|
||||
"kubernetes": {
|
||||
"labels": {},
|
||||
Optional("namespace"): str,
|
||||
Optional("scope_label"): str,
|
||||
Optional("role_label"): str,
|
||||
Optional("use_endpoints"): bool,
|
||||
Optional("pod_ip"): Or(is_ipv4_address, is_ipv6_address),
|
||||
Optional("ports"): [{"name": str, "port": int}],
|
||||
},
|
||||
}),
|
||||
"postgresql": {
|
||||
"listen": validate_host_port_listen_multiple_hosts,
|
||||
"connect_address": validate_connect_address,
|
||||
"authentication": {
|
||||
"replication": userattributes,
|
||||
"superuser": userattributes,
|
||||
"rewind": userattributes
|
||||
},
|
||||
"data_dir": validate_data_dir,
|
||||
Optional("bin_dir"): Directory(contains_executable=["pg_ctl", "initdb", "pg_controldata", "pg_basebackup",
|
||||
"postgres", "pg_isready"]),
|
||||
Optional("parameters"): {
|
||||
Optional("unix_socket_directories"): lambda s: assert_(all([isinstance(s, string_types), len(s)]))
|
||||
},
|
||||
Optional("pg_hba"): [str],
|
||||
Optional("pg_ident"): [str],
|
||||
Optional("pg_ctl_timeout"): int,
|
||||
Optional("use_pg_rewind"): bool
|
||||
},
|
||||
Optional("watchdog"): {
|
||||
Optional("mode"): lambda m: assert_(m in ["off", "automatic", "required"]),
|
||||
Optional("device"): str
|
||||
},
|
||||
Optional("tags"): {
|
||||
Optional("nofailover"): bool,
|
||||
Optional("clonefrom"): bool,
|
||||
Optional("noloadbalance"): bool,
|
||||
Optional("replicatefrom"): str,
|
||||
Optional("nosync"): bool
|
||||
}
|
||||
})
|
||||
+1
-1
@@ -1 +1 @@
|
||||
__version__ = '1.2.5'
|
||||
__version__ = '1.6.5'
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
from patroni.watchdog.base import WatchdogError, Watchdog
|
||||
__all__ = ['WatchdogError', 'Watchdog']
|
||||
@@ -0,0 +1,313 @@
|
||||
import abc
|
||||
import logging
|
||||
import platform
|
||||
import six
|
||||
import sys
|
||||
from threading import RLock
|
||||
|
||||
from patroni.exceptions import WatchdogError
|
||||
|
||||
__all__ = ['WatchdogError', 'Watchdog']
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MODE_REQUIRED = 'required' # Will not run if a watchdog is not available
|
||||
MODE_AUTOMATIC = 'automatic' # Will use a watchdog if one is available
|
||||
MODE_OFF = 'off' # Will not try to use a watchdog
|
||||
|
||||
|
||||
def parse_mode(mode):
|
||||
if mode is False:
|
||||
return MODE_OFF
|
||||
mode = mode.lower()
|
||||
if mode in ['require', 'required']:
|
||||
return MODE_REQUIRED
|
||||
elif mode in ['auto', 'automatic']:
|
||||
return MODE_AUTOMATIC
|
||||
else:
|
||||
if mode not in ['off', 'disable', 'disabled']:
|
||||
logger.warning("Watchdog mode {0} not recognized, disabling watchdog".format(mode))
|
||||
return MODE_OFF
|
||||
|
||||
|
||||
def synchronized(func):
|
||||
def wrapped(self, *args, **kwargs):
|
||||
with self._lock:
|
||||
return func(self, *args, **kwargs)
|
||||
return wrapped
|
||||
|
||||
|
||||
class WatchdogConfig(object):
|
||||
"""Helper to contain a snapshot of configuration"""
|
||||
def __init__(self, config):
|
||||
self.mode = parse_mode(config['watchdog'].get('mode', 'automatic'))
|
||||
self.ttl = config['ttl']
|
||||
self.loop_wait = config['loop_wait']
|
||||
self.safety_margin = config['watchdog'].get('safety_margin', 5)
|
||||
self.driver = config['watchdog'].get('driver', 'default')
|
||||
self.driver_config = dict((k, v) for k, v in config['watchdog'].items()
|
||||
if k not in ['mode', 'safety_margin', 'driver'])
|
||||
|
||||
def __eq__(self, other):
|
||||
return isinstance(other, WatchdogConfig) and \
|
||||
all(getattr(self, attr) == getattr(other, attr) for attr in
|
||||
['mode', 'ttl', 'loop_wait', 'safety_margin', 'driver', 'driver_config'])
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def get_impl(self):
|
||||
if self.driver == 'testing': # pragma: no cover
|
||||
from patroni.watchdog.linux import TestingWatchdogDevice
|
||||
return TestingWatchdogDevice.from_config(self.driver_config)
|
||||
elif platform.system() == 'Linux' and self.driver == 'default':
|
||||
from patroni.watchdog.linux import LinuxWatchdogDevice
|
||||
return LinuxWatchdogDevice.from_config(self.driver_config)
|
||||
else:
|
||||
return NullWatchdog()
|
||||
|
||||
@property
|
||||
def timeout(self):
|
||||
if self.safety_margin == -1:
|
||||
return int(self.ttl // 2)
|
||||
else:
|
||||
return self.ttl - self.safety_margin
|
||||
|
||||
@property
|
||||
def timing_slack(self):
|
||||
return self.timeout - self.loop_wait
|
||||
|
||||
|
||||
class Watchdog(object):
|
||||
"""Facade to dynamically manage watchdog implementations and handle config changes.
|
||||
|
||||
When activation fails underlying implementation will be switched to a Null implementation. To avoid log spam
|
||||
activation will only be retried when watchdog configuration is changed."""
|
||||
def __init__(self, config):
|
||||
self.active_config = self.config = WatchdogConfig(config)
|
||||
self._lock = RLock()
|
||||
self.active = False
|
||||
|
||||
if self.config.mode == MODE_OFF:
|
||||
self.impl = NullWatchdog()
|
||||
else:
|
||||
self.impl = self.config.get_impl()
|
||||
if self.config.mode == MODE_REQUIRED and self.impl.is_null:
|
||||
logger.error("Configuration requires a watchdog, but watchdog is not supported on this platform.")
|
||||
sys.exit(1)
|
||||
|
||||
@synchronized
|
||||
def reload_config(self, config):
|
||||
self.config = WatchdogConfig(config)
|
||||
# Turning a watchdog off can always be done immediately
|
||||
if self.config.mode == MODE_OFF:
|
||||
if self.active:
|
||||
self._disable()
|
||||
self.active_config = self.config
|
||||
self.impl = NullWatchdog()
|
||||
# If watchdog is not active we can apply config immediately to show any warnings early. Otherwise we need to
|
||||
# delay until next time a keepalive is sent so timeout matches up with leader key update.
|
||||
if not self.active:
|
||||
if self.config.driver != self.active_config.driver or \
|
||||
self.config.driver_config != self.active_config.driver_config:
|
||||
self.impl = self.config.get_impl()
|
||||
self.active_config = self.config
|
||||
|
||||
@synchronized
|
||||
def activate(self):
|
||||
"""Activates the watchdog device with suitable timeouts. While watchdog is active keepalive needs
|
||||
to be called every time loop_wait expires.
|
||||
|
||||
:returns False if a safe watchdog could not be configured, but is required.
|
||||
"""
|
||||
self.active = True
|
||||
return self._activate()
|
||||
|
||||
def _activate(self):
|
||||
self.active_config = self.config
|
||||
|
||||
if self.config.timing_slack < 0:
|
||||
logger.warning('Watchdog not supported because leader TTL {0} is less than 2x loop_wait {1}'
|
||||
.format(self.config.ttl, self.config.loop_wait))
|
||||
self.impl = NullWatchdog()
|
||||
|
||||
try:
|
||||
self.impl.open()
|
||||
actual_timeout = self._set_timeout()
|
||||
except WatchdogError as e:
|
||||
logger.warning("Could not activate %s: %s", self.impl.describe(), e)
|
||||
self.impl = NullWatchdog()
|
||||
|
||||
if self.impl.is_running and not self.impl.can_be_disabled:
|
||||
logger.warning("Watchdog implementation can't be disabled."
|
||||
" Watchdog will trigger after Patroni loses leader key.")
|
||||
|
||||
if not self.impl.is_running or actual_timeout > self.config.timeout:
|
||||
if self.config.mode == MODE_REQUIRED:
|
||||
if self.impl.is_null:
|
||||
logger.error("Configuration requires watchdog, but watchdog could not be configured.")
|
||||
else:
|
||||
logger.error("Configuration requires watchdog, but a safe watchdog timeout {0} could"
|
||||
" not be configured. Watchdog timeout is {1}.".format(
|
||||
self.config.timeout, actual_timeout))
|
||||
return False
|
||||
else:
|
||||
if not self.impl.is_null:
|
||||
logger.warning("Watchdog timeout {0} seconds does not ensure safe termination within {1} seconds"
|
||||
.format(actual_timeout, self.config.timeout))
|
||||
|
||||
if self.is_running:
|
||||
logger.info("{0} activated with {1} second timeout, timing slack {2} seconds"
|
||||
.format(self.impl.describe(), actual_timeout, self.config.timing_slack))
|
||||
else:
|
||||
if self.config.mode == MODE_REQUIRED:
|
||||
logger.error("Configuration requires watchdog, but watchdog could not be activated")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _set_timeout(self):
|
||||
if self.impl.has_set_timeout():
|
||||
self.impl.set_timeout(self.config.timeout)
|
||||
|
||||
# Safety checks for watchdog implementations that don't support configurable timeouts
|
||||
actual_timeout = self.impl.get_timeout()
|
||||
if self.impl.is_running and actual_timeout < self.config.loop_wait:
|
||||
logger.error('loop_wait of {0} seconds is too long for watchdog {1} second timeout'
|
||||
.format(self.config.loop_wait, actual_timeout))
|
||||
if self.impl.can_be_disabled:
|
||||
logger.info('Disabling watchdog due to unsafe timeout.')
|
||||
self.impl.close()
|
||||
self.impl = NullWatchdog()
|
||||
return None
|
||||
return actual_timeout
|
||||
|
||||
@synchronized
|
||||
def disable(self):
|
||||
self._disable()
|
||||
self.active = False
|
||||
|
||||
def _disable(self):
|
||||
try:
|
||||
if self.impl.is_running and not self.impl.can_be_disabled:
|
||||
# Give sysadmin some extra time to clean stuff up.
|
||||
self.impl.keepalive()
|
||||
logger.warning("Watchdog implementation can't be disabled. System will reboot after "
|
||||
"{0} seconds when watchdog times out.".format(self.impl.get_timeout()))
|
||||
self.impl.close()
|
||||
except WatchdogError as e:
|
||||
logger.error("Error while disabling watchdog: %s", e)
|
||||
|
||||
@synchronized
|
||||
def keepalive(self):
|
||||
try:
|
||||
if self.active:
|
||||
self.impl.keepalive()
|
||||
# In case there are any pending configuration changes apply them now.
|
||||
if self.active and self.config != self.active_config:
|
||||
if self.config.mode != MODE_OFF and self.active_config.mode == MODE_OFF:
|
||||
self.impl = self.config.get_impl()
|
||||
self._activate()
|
||||
if self.config.driver != self.active_config.driver \
|
||||
or self.config.driver_config != self.active_config.driver_config:
|
||||
self._disable()
|
||||
self.impl = self.config.get_impl()
|
||||
self._activate()
|
||||
if self.config.timeout != self.active_config.timeout:
|
||||
self.impl.set_timeout(self.config.timeout)
|
||||
except WatchdogError as e:
|
||||
logger.error("Error while sending keepalive: %s", e)
|
||||
|
||||
@property
|
||||
@synchronized
|
||||
def is_running(self):
|
||||
return self.impl.is_running
|
||||
|
||||
@property
|
||||
@synchronized
|
||||
def is_healthy(self):
|
||||
if self.config.mode != MODE_REQUIRED:
|
||||
return True
|
||||
return self.config.timing_slack >= 0 and self.impl.is_healthy
|
||||
|
||||
|
||||
@six.add_metaclass(abc.ABCMeta)
|
||||
class WatchdogBase(object):
|
||||
"""A watchdog object when opened requires periodic calls to keepalive.
|
||||
When keepalive is not called within a timeout the system will be terminated."""
|
||||
is_null = False
|
||||
|
||||
@property
|
||||
def is_running(self):
|
||||
"""Returns True when watchdog is activated and capable of performing it's task."""
|
||||
return False
|
||||
|
||||
@property
|
||||
def is_healthy(self):
|
||||
"""Returns False when calling open() is known to fail."""
|
||||
return False
|
||||
|
||||
@property
|
||||
def can_be_disabled(self):
|
||||
"""Returns True when watchdog will be disabled by calling close(). Some watchdog devices
|
||||
will keep running no matter what once activated. May raise WatchdogError if called without
|
||||
calling open() first."""
|
||||
return True
|
||||
|
||||
@abc.abstractmethod
|
||||
def open(self):
|
||||
"""Open watchdog device.
|
||||
|
||||
When watchdog is opened keepalive must be called. Returns nothing on success
|
||||
or raises WatchdogError if the device could not be opened."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def close(self):
|
||||
"""Gracefully close watchdog device."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def keepalive(self):
|
||||
"""Resets the watchdog timer.
|
||||
|
||||
Watchdog must be open when keepalive is called."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_timeout(self):
|
||||
"""Returns the current keepalive timeout in effect."""
|
||||
|
||||
@staticmethod
|
||||
def has_set_timeout():
|
||||
"""Returns True if setting a timeout is supported."""
|
||||
return False
|
||||
|
||||
def set_timeout(self, timeout):
|
||||
"""Set the watchdog timer timeout.
|
||||
|
||||
:param timeout: watchdog timeout in seconds"""
|
||||
raise WatchdogError("Setting timeout is not supported on {0}".format(self.describe()))
|
||||
|
||||
def describe(self):
|
||||
"""Human readable name for this device"""
|
||||
return self.__class__.__name__
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config):
|
||||
return cls()
|
||||
|
||||
|
||||
class NullWatchdog(WatchdogBase):
|
||||
"""Null implementation when watchdog is not supported."""
|
||||
is_null = True
|
||||
|
||||
def open(self):
|
||||
return
|
||||
|
||||
def close(self):
|
||||
return
|
||||
|
||||
def keepalive(self):
|
||||
return
|
||||
|
||||
def get_timeout(self):
|
||||
# A big enough number to not matter
|
||||
return 1000000000
|
||||
@@ -0,0 +1,235 @@
|
||||
import collections
|
||||
import ctypes
|
||||
import os
|
||||
import platform
|
||||
from patroni.watchdog.base import WatchdogBase, WatchdogError
|
||||
|
||||
# Pythonification of linux/ioctl.h
|
||||
IOC_NONE = 0
|
||||
IOC_WRITE = 1
|
||||
IOC_READ = 2
|
||||
|
||||
IOC_NRBITS = 8
|
||||
IOC_TYPEBITS = 8
|
||||
IOC_SIZEBITS = 14
|
||||
IOC_DIRBITS = 2
|
||||
|
||||
# Non-generic platform special cases
|
||||
machine = platform.machine()
|
||||
if machine in ['mips', 'sparc', 'powerpc', 'ppc64']: # pragma: no cover
|
||||
IOC_SIZEBITS = 13
|
||||
IOC_DIRBITS = 3
|
||||
IOC_NONE, IOC_WRITE, IOC_READ = 1, 2, 4
|
||||
elif machine == 'parisc': # pragma: no cover
|
||||
IOC_WRITE, IOC_READ = 2, 1
|
||||
|
||||
IOC_NRSHIFT = 0
|
||||
IOC_TYPESHIFT = IOC_NRSHIFT + IOC_NRBITS
|
||||
IOC_SIZESHIFT = IOC_TYPESHIFT + IOC_TYPEBITS
|
||||
IOC_DIRSHIFT = IOC_SIZESHIFT + IOC_SIZEBITS
|
||||
|
||||
|
||||
def IOW(type_, nr, size):
|
||||
return IOC(IOC_WRITE, type_, nr, size)
|
||||
|
||||
|
||||
def IOR(type_, nr, size):
|
||||
return IOC(IOC_READ, type_, nr, size)
|
||||
|
||||
|
||||
def IOWR(type_, nr, size):
|
||||
return IOC(IOC_READ | IOC_WRITE, type_, nr, size)
|
||||
|
||||
|
||||
def IOC(dir_, type_, nr, size):
|
||||
return (dir_ << IOC_DIRSHIFT) \
|
||||
| (ord(type_) << IOC_TYPESHIFT) \
|
||||
| (nr << IOC_NRSHIFT) \
|
||||
| (size << IOC_SIZESHIFT)
|
||||
|
||||
|
||||
# Pythonification of linux/watchdog.h
|
||||
|
||||
WATCHDOG_IOCTL_BASE = 'W'
|
||||
|
||||
|
||||
class watchdog_info(ctypes.Structure):
|
||||
_fields_ = [
|
||||
('options', ctypes.c_uint32), # Options the card/driver supports
|
||||
('firmware_version', ctypes.c_uint32), # Firmware version of the card
|
||||
('identity', ctypes.c_uint8 * 32), # Identity of the board
|
||||
]
|
||||
|
||||
|
||||
struct_watchdog_info_size = ctypes.sizeof(watchdog_info)
|
||||
int_size = ctypes.sizeof(ctypes.c_int)
|
||||
|
||||
WDIOC_GETSUPPORT = IOR(WATCHDOG_IOCTL_BASE, 0, struct_watchdog_info_size)
|
||||
WDIOC_GETSTATUS = IOR(WATCHDOG_IOCTL_BASE, 1, int_size)
|
||||
WDIOC_GETBOOTSTATUS = IOR(WATCHDOG_IOCTL_BASE, 2, int_size)
|
||||
WDIOC_GETTEMP = IOR(WATCHDOG_IOCTL_BASE, 3, int_size)
|
||||
WDIOC_SETOPTIONS = IOR(WATCHDOG_IOCTL_BASE, 4, int_size)
|
||||
WDIOC_KEEPALIVE = IOR(WATCHDOG_IOCTL_BASE, 5, int_size)
|
||||
WDIOC_SETTIMEOUT = IOWR(WATCHDOG_IOCTL_BASE, 6, int_size)
|
||||
WDIOC_GETTIMEOUT = IOR(WATCHDOG_IOCTL_BASE, 7, int_size)
|
||||
WDIOC_SETPRETIMEOUT = IOWR(WATCHDOG_IOCTL_BASE, 8, int_size)
|
||||
WDIOC_GETPRETIMEOUT = IOR(WATCHDOG_IOCTL_BASE, 9, int_size)
|
||||
WDIOC_GETTIMELEFT = IOR(WATCHDOG_IOCTL_BASE, 10, int_size)
|
||||
|
||||
|
||||
WDIOF_UNKNOWN = -1 # Unknown flag error
|
||||
WDIOS_UNKNOWN = -1 # Unknown status error
|
||||
|
||||
WDIOF = {
|
||||
"OVERHEAT": 0x0001, # Reset due to CPU overheat
|
||||
"FANFAULT": 0x0002, # Fan failed
|
||||
"EXTERN1": 0x0004, # External relay 1
|
||||
"EXTERN2": 0x0008, # External relay 2
|
||||
"POWERUNDER": 0x0010, # Power bad/power fault
|
||||
"CARDRESET": 0x0020, # Card previously reset the CPU
|
||||
"POWEROVER": 0x0040, # Power over voltage
|
||||
"SETTIMEOUT": 0x0080, # Set timeout (in seconds)
|
||||
"MAGICCLOSE": 0x0100, # Supports magic close char
|
||||
"PRETIMEOUT": 0x0200, # Pretimeout (in seconds), get/set
|
||||
"ALARMONLY": 0x0400, # Watchdog triggers a management or other external alarm not a reboot
|
||||
"KEEPALIVEPING": 0x8000, # Keep alive ping reply
|
||||
}
|
||||
|
||||
WDIOS = {
|
||||
"DISABLECARD": 0x0001, # Turn off the watchdog timer
|
||||
"ENABLECARD": 0x0002, # Turn on the watchdog timer
|
||||
"TEMPPANIC": 0x0004, # Kernel panic on temperature trip
|
||||
}
|
||||
|
||||
# Implementation
|
||||
|
||||
|
||||
class WatchdogInfo(collections.namedtuple('WatchdogInfo', 'options,version,identity')):
|
||||
"""Watchdog descriptor from the kernel"""
|
||||
def __getattr__(self, name):
|
||||
"""Convenience has_XYZ attributes for checking WDIOF bits in options"""
|
||||
if name.startswith('has_') and name[4:] in WDIOF:
|
||||
return bool(self.options & WDIOF[name[4:]])
|
||||
|
||||
raise AttributeError("WatchdogInfo instance has no attribute '{0}'".format(name))
|
||||
|
||||
|
||||
class LinuxWatchdogDevice(WatchdogBase):
|
||||
DEFAULT_DEVICE = '/dev/watchdog'
|
||||
|
||||
def __init__(self, device):
|
||||
self.device = device
|
||||
self._support_cache = None
|
||||
self._fd = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config):
|
||||
device = config.get('device', cls.DEFAULT_DEVICE)
|
||||
return cls(device)
|
||||
|
||||
@property
|
||||
def is_running(self):
|
||||
return self._fd is not None
|
||||
|
||||
@property
|
||||
def is_healthy(self):
|
||||
return os.path.exists(self.device) and os.access(self.device, os.W_OK)
|
||||
|
||||
def open(self):
|
||||
try:
|
||||
self._fd = os.open(self.device, os.O_WRONLY)
|
||||
except OSError as e:
|
||||
raise WatchdogError("Can't open watchdog device: {0}".format(e))
|
||||
|
||||
def close(self):
|
||||
if self.is_running:
|
||||
try:
|
||||
os.write(self._fd, b'V')
|
||||
os.close(self._fd)
|
||||
self._fd = None
|
||||
except OSError as e:
|
||||
raise WatchdogError("Error while closing {0}: {1}".format(self.describe(), e))
|
||||
|
||||
@property
|
||||
def can_be_disabled(self):
|
||||
return self.get_support().has_MAGICCLOSE
|
||||
|
||||
def _ioctl(self, func, arg):
|
||||
"""Runs the specified ioctl on the underlying fd.
|
||||
|
||||
Raises WatchdogError if the device is closed.
|
||||
Raises OSError or IOError (Python 2) when the ioctl fails."""
|
||||
if self._fd is None:
|
||||
raise WatchdogError("Watchdog device is closed")
|
||||
if os.name != 'nt':
|
||||
import fcntl
|
||||
fcntl.ioctl(self._fd, func, arg, True)
|
||||
|
||||
def get_support(self):
|
||||
if self._support_cache is None:
|
||||
info = watchdog_info()
|
||||
try:
|
||||
self._ioctl(WDIOC_GETSUPPORT, info)
|
||||
except (WatchdogError, OSError, IOError) as e:
|
||||
raise WatchdogError("Could not get information about watchdog device: {}".format(e))
|
||||
self._support_cache = WatchdogInfo(info.options,
|
||||
info.firmware_version,
|
||||
bytearray(info.identity).decode(errors='ignore').rstrip('\x00'))
|
||||
return self._support_cache
|
||||
|
||||
def describe(self):
|
||||
dev_str = " at {0}".format(self.device) if self.device != self.DEFAULT_DEVICE else ""
|
||||
ver_str = ""
|
||||
identity = "Linux watchdog device"
|
||||
if self._fd:
|
||||
try:
|
||||
_, version, identity = self.get_support()
|
||||
ver_str = " (firmware {0})".format(version) if version else ""
|
||||
except WatchdogError:
|
||||
pass
|
||||
|
||||
return identity + ver_str + dev_str
|
||||
|
||||
def keepalive(self):
|
||||
try:
|
||||
os.write(self._fd, b'1')
|
||||
except OSError as e:
|
||||
raise WatchdogError("Could not send watchdog keepalive: {0}".format(e))
|
||||
|
||||
def has_set_timeout(self):
|
||||
"""Returns True if setting a timeout is supported."""
|
||||
return self.get_support().has_SETTIMEOUT
|
||||
|
||||
def set_timeout(self, timeout):
|
||||
timeout = int(timeout)
|
||||
if not 0 < timeout < 0xFFFF:
|
||||
raise WatchdogError("Invalid timeout {0}. Supported values are between 1 and 65535".format(timeout))
|
||||
try:
|
||||
self._ioctl(WDIOC_SETTIMEOUT, ctypes.c_int(timeout))
|
||||
except (WatchdogError, OSError, IOError) as e:
|
||||
raise WatchdogError("Could not set timeout on watchdog device: {}".format(e))
|
||||
|
||||
def get_timeout(self):
|
||||
timeout = ctypes.c_int()
|
||||
try:
|
||||
self._ioctl(WDIOC_GETTIMEOUT, timeout)
|
||||
except (WatchdogError, OSError, IOError) as e:
|
||||
raise WatchdogError("Could not get timeout on watchdog device: {}".format(e))
|
||||
return timeout.value
|
||||
|
||||
|
||||
class TestingWatchdogDevice(LinuxWatchdogDevice): # pragma: no cover
|
||||
"""Converts timeout ioctls to regular writes that can be intercepted from a named pipe."""
|
||||
timeout = 60
|
||||
|
||||
def get_support(self):
|
||||
return WatchdogInfo(WDIOF['MAGICCLOSE'] | WDIOF['SETTIMEOUT'], 0, "Watchdog test harness")
|
||||
|
||||
def set_timeout(self, timeout):
|
||||
buf = "Ctimeout={0}\n".format(timeout).encode('utf8')
|
||||
while len(buf):
|
||||
buf = buf[os.write(self._fd, buf):]
|
||||
self.timeout = timeout
|
||||
|
||||
def get_timeout(self):
|
||||
return self.timeout
|
||||
+40
-2
@@ -11,8 +11,24 @@ restapi:
|
||||
# username: username
|
||||
# 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:
|
||||
#Provide host to do the initial discovery of the cluster topology:
|
||||
host: 127.0.0.1:2379
|
||||
#Or use "hosts" to provide multiple endpoints
|
||||
#Could be a comma separated string:
|
||||
#hosts: host1:port1,host2:port2
|
||||
#or an actual yaml list:
|
||||
#hosts:
|
||||
#- host1:port1
|
||||
#- host2:port2
|
||||
#Once discovery is complete Patroni will use the list of advertised clientURLs
|
||||
#It is possible to change this behavior through by setting:
|
||||
#use_proxies: true
|
||||
|
||||
bootstrap:
|
||||
# this section will be written into Etcd:/<namespace>/<scope>/config after initializing new cluster
|
||||
@@ -24,6 +40,10 @@ bootstrap:
|
||||
maximum_lag_on_failover: 1048576
|
||||
# master_start_timeout: 300
|
||||
# synchronous_mode: false
|
||||
#standby_cluster:
|
||||
#host: 127.0.0.1
|
||||
#port: 1111
|
||||
#primary_slot_name: patroni
|
||||
postgresql:
|
||||
use_pg_rewind: true
|
||||
# use_slots: true
|
||||
@@ -31,8 +51,8 @@ bootstrap:
|
||||
# wal_level: hot_standby
|
||||
# hot_standby: "on"
|
||||
# wal_keep_segments: 8
|
||||
# max_wal_senders: 5
|
||||
# max_replication_slots: 5
|
||||
# max_wal_senders: 10
|
||||
# max_replication_slots: 10
|
||||
# wal_log_hints: "on"
|
||||
# archive_mode: "on"
|
||||
# archive_timeout: 1800s
|
||||
@@ -46,6 +66,9 @@ bootstrap:
|
||||
- data-checksums
|
||||
|
||||
pg_hba: # Add following lines to pg_hba.conf after running 'initdb'
|
||||
# For kerberos gss based connectivity (discard @.*$)
|
||||
#- host replication replicator 127.0.0.1/32 gss include_realm=0
|
||||
#- host all all 0.0.0.0/0 gss include_realm=0
|
||||
- host replication replicator 127.0.0.1/32 md5
|
||||
- host all all 0.0.0.0/0 md5
|
||||
# - hostssl all all 0.0.0.0/0 md5
|
||||
@@ -66,6 +89,7 @@ postgresql:
|
||||
connect_address: 127.0.0.1:5432
|
||||
data_dir: data/postgresql0
|
||||
# bin_dir:
|
||||
# config_dir:
|
||||
pgpass: /tmp/pgpass0
|
||||
authentication:
|
||||
replication:
|
||||
@@ -74,8 +98,22 @@ postgresql:
|
||||
superuser:
|
||||
username: postgres
|
||||
password: zalando
|
||||
rewind: # Has no effect on postgres 10 and lower
|
||||
username: rewind_user
|
||||
password: rewind_password
|
||||
# Server side kerberos spn
|
||||
# krbsrvname: postgres
|
||||
parameters:
|
||||
# Fully qualified kerberos ticket file for the running user
|
||||
# same as KRB5CCNAME used by the GSS
|
||||
# krb_server_keyfile: /var/spool/keytabs/postgres
|
||||
unix_socket_directories: '.'
|
||||
|
||||
#watchdog:
|
||||
# mode: automatic # Allowed values: off, automatic, required
|
||||
# device: /dev/watchdog
|
||||
# safety_margin: 5
|
||||
|
||||
tags:
|
||||
nofailover: false
|
||||
noloadbalance: false
|
||||
|
||||
+33
-2
@@ -11,8 +11,24 @@ restapi:
|
||||
# username: username
|
||||
# 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:
|
||||
#Provide host to do the initial discovery of the cluster topology:
|
||||
host: 127.0.0.1:2379
|
||||
#Or use "hosts" to provide multiple endpoints
|
||||
#Could be a comma separated string:
|
||||
#hosts: host1:port1,host2:port2
|
||||
#or an actual yaml list:
|
||||
#hosts:
|
||||
#- host1:port1
|
||||
#- host2:port2
|
||||
#Once discovery is complete Patroni will use the list of advertised clientURLs
|
||||
#It is possible to change this behavior through by setting:
|
||||
#use_proxies: true
|
||||
|
||||
bootstrap:
|
||||
# this section will be written into Etcd:/<namespace>/<scope>/config after initializing new cluster
|
||||
@@ -29,8 +45,8 @@ bootstrap:
|
||||
# wal_level: hot_standby
|
||||
# hot_standby: "on"
|
||||
# wal_keep_segments: 8
|
||||
# max_wal_senders: 5
|
||||
# max_replication_slots: 5
|
||||
# max_wal_senders: 10
|
||||
# max_replication_slots: 10
|
||||
# wal_log_hints: "on"
|
||||
# archive_mode: "on"
|
||||
# archive_timeout: 1800s
|
||||
@@ -44,6 +60,9 @@ bootstrap:
|
||||
- data-checksums
|
||||
|
||||
pg_hba: # Add following lines to pg_hba.conf after running 'initdb'
|
||||
# For kerberos gss based connectivity (discard @.*$)
|
||||
#- host replication replicator 127.0.0.1/32 gss include_realm=0
|
||||
#- host all all 0.0.0.0/0 gss include_realm=0
|
||||
- host replication replicator 127.0.0.1/32 md5
|
||||
- host all all 0.0.0.0/0 md5
|
||||
# - hostssl all all 0.0.0.0/0 md5
|
||||
@@ -64,6 +83,7 @@ postgresql:
|
||||
connect_address: 127.0.0.1:5433
|
||||
data_dir: data/postgresql1
|
||||
# bin_dir:
|
||||
# config_dir:
|
||||
pgpass: /tmp/pgpass1
|
||||
authentication:
|
||||
replication:
|
||||
@@ -72,8 +92,19 @@ postgresql:
|
||||
superuser:
|
||||
username: postgres
|
||||
password: zalando
|
||||
rewind: # Has no effect on postgres 10 and lower
|
||||
username: rewind_user
|
||||
password: rewind_password
|
||||
# Server side kerberos spn
|
||||
# krbsrvname: postgres
|
||||
parameters:
|
||||
# Fully qualified kerberos ticket file for the running user
|
||||
# same as KRB5CCNAME used by the GSS
|
||||
# krb_server_keyfile: /var/spool/keytabs/postgres
|
||||
unix_socket_directories: '.'
|
||||
basebackup:
|
||||
- verbose
|
||||
- max-rate: 100M
|
||||
tags:
|
||||
nofailover: false
|
||||
noloadbalance: false
|
||||
|
||||
+30
-2
@@ -11,8 +11,24 @@ restapi:
|
||||
username: username
|
||||
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:
|
||||
#Provide host to do the initial discovery of the cluster topology:
|
||||
host: 127.0.0.1:2379
|
||||
#Or use "hosts" to provide multiple endpoints
|
||||
#Could be a comma separated string:
|
||||
#hosts: host1:port1,host2:port2
|
||||
#or an actual yaml list:
|
||||
#hosts:
|
||||
#- host1:port1
|
||||
#- host2:port2
|
||||
#Once discovery is complete Patroni will use the list of advertised clientURLs
|
||||
#It is possible to change this behavior through by setting:
|
||||
#use_proxies: true
|
||||
|
||||
bootstrap:
|
||||
# this section will be written into Etcd:/<namespace>/<scope>/config after initializing new cluster
|
||||
@@ -29,8 +45,8 @@ bootstrap:
|
||||
# wal_level: hot_standby
|
||||
# hot_standby: "on"
|
||||
# wal_keep_segments: 8
|
||||
# max_wal_senders: 5
|
||||
# max_replication_slots: 5
|
||||
# max_wal_senders: 10
|
||||
# max_replication_slots: 10
|
||||
# wal_log_hints: "on"
|
||||
# archive_mode: "on"
|
||||
# archive_timeout: 1800s
|
||||
@@ -44,6 +60,9 @@ bootstrap:
|
||||
- data-checksums
|
||||
|
||||
pg_hba: # Add following lines to pg_hba.conf after running 'initdb'
|
||||
# For kerberos gss based connectivity (discard @.*$)
|
||||
#- host replication replicator 127.0.0.1/32 gss include_realm=0
|
||||
#- host all all 0.0.0.0/0 gss include_realm=0
|
||||
- host replication replicator 127.0.0.1/32 md5
|
||||
- host all all 0.0.0.0/0 md5
|
||||
# - hostssl all all 0.0.0.0/0 md5
|
||||
@@ -61,6 +80,7 @@ postgresql:
|
||||
connect_address: 127.0.0.1:5434
|
||||
data_dir: data/postgresql2
|
||||
# bin_dir:
|
||||
# config_dir:
|
||||
pgpass: /tmp/pgpass2
|
||||
authentication:
|
||||
replication:
|
||||
@@ -69,7 +89,15 @@ postgresql:
|
||||
superuser:
|
||||
username: postgres
|
||||
password: zalando
|
||||
rewind: # Has no effect on postgres 10 and lower
|
||||
username: rewind_user
|
||||
password: rewind_password
|
||||
# Server side kerberos spn
|
||||
# krbsrvname: postgres
|
||||
parameters:
|
||||
# Fully qualified kerberos ticket file for the running user
|
||||
# same as KRB5CCNAME used by the GSS
|
||||
# krb_server_keyfile: /var/spool/keytabs/postgres
|
||||
unix_socket_directories: '.'
|
||||
tags:
|
||||
nofailover: false
|
||||
|
||||
+8
-8
@@ -1,13 +1,13 @@
|
||||
urllib3>=1.9
|
||||
urllib3>=1.19.1,!=1.21
|
||||
boto
|
||||
psycopg2>=2.6.1
|
||||
PyYAML
|
||||
requests
|
||||
six >= 1.7
|
||||
kazoo==2.2.1
|
||||
python-etcd==0.4.3
|
||||
python-consul==0.7.0
|
||||
kazoo>=1.3.1
|
||||
python-etcd>=0.4.3,<0.5
|
||||
python-consul>=0.7.1
|
||||
click>=4.1
|
||||
prettytable>=0.7
|
||||
tzlocal
|
||||
texttable
|
||||
python-dateutil
|
||||
psutil>=2.0.0
|
||||
cdiff
|
||||
kubernetes>=2.0.0,<=10.0.1,!=4.0.*,!=5.0.*
|
||||
|
||||
@@ -8,51 +8,44 @@ import inspect
|
||||
import os
|
||||
import sys
|
||||
|
||||
from setuptools.command.test import test as TestCommand
|
||||
from setuptools import find_packages, setup
|
||||
|
||||
if sys.version_info < (2, 7, 0):
|
||||
sys.stderr.write('FATAL: patroni needs to be run with Python 2.7+\n')
|
||||
sys.exit(1)
|
||||
from setuptools import Command, find_packages, setup
|
||||
|
||||
__location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())))
|
||||
|
||||
|
||||
def read_version(package):
|
||||
data = {}
|
||||
with open(os.path.join(package, 'version.py'), 'r') as fd:
|
||||
exec(fd.read(), data)
|
||||
return data['__version__']
|
||||
|
||||
|
||||
NAME = 'patroni'
|
||||
MAIN_PACKAGE = NAME
|
||||
SCRIPTS = 'scripts'
|
||||
VERSION = read_version(MAIN_PACKAGE)
|
||||
DESCRIPTION = 'PostgreSQL High-Available orchestrator and CLI'
|
||||
LICENSE = 'The MIT License'
|
||||
URL = 'https://github.com/zalando/patroni'
|
||||
AUTHOR = 'Alexander Kukushkin, Oleksii Kliukin, Feike Steenbergen'
|
||||
AUTHOR_EMAIL = '[email protected], [email protected], [email protected]'
|
||||
KEYWORDS = 'etcd governor patroni postgresql postgres ha haproxy confd zookeeper exhibitor consul streaming replication'
|
||||
AUTHOR = 'Alexander Kukushkin, Dmitrii Dolgov, Oleksii Kliukin'
|
||||
AUTHOR_EMAIL = '[email protected], [email protected], [email protected]'
|
||||
KEYWORDS = 'etcd governor patroni postgresql postgres ha haproxy confd' +\
|
||||
' zookeeper exhibitor consul streaming replication kubernetes k8s'
|
||||
|
||||
EXTRAS_REQUIRE = {'aws': ['boto'], 'etcd': ['python-etcd'], 'consul': ['python-consul'],
|
||||
'exhibitor': ['kazoo'], 'zookeeper': ['kazoo'], 'kubernetes': ['kubernetes']}
|
||||
COVERAGE_XML = True
|
||||
COVERAGE_HTML = False
|
||||
JUNIT_XML = True
|
||||
|
||||
# Add here all kinds of additional classifiers as defined under
|
||||
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
|
||||
CLASSIFIERS = [
|
||||
'Development Status :: 4 - Beta',
|
||||
'Development Status :: 5 - Production/Stable',
|
||||
'Environment :: Console',
|
||||
'Intended Audience :: Developers',
|
||||
'Intended Audience :: System Administrators',
|
||||
'License :: OSI Approved :: MIT License',
|
||||
'Operating System :: MacOS',
|
||||
'Operating System :: POSIX :: Linux',
|
||||
'Operating System :: POSIX :: BSD :: FreeBSD',
|
||||
'Operating System :: Microsoft :: Windows',
|
||||
'Programming Language :: Python',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Programming Language :: Python :: 3.4',
|
||||
'Programming Language :: Python :: 3.5',
|
||||
'Programming Language :: Python :: 3.6',
|
||||
'Programming Language :: Python :: 3.7',
|
||||
'Programming Language :: Python :: Implementation :: CPython',
|
||||
]
|
||||
|
||||
@@ -62,70 +55,123 @@ CONSOLE_SCRIPTS = ['patroni = patroni:main',
|
||||
"patroni_aws = patroni.scripts.aws:main"]
|
||||
|
||||
|
||||
class PyTest(TestCommand):
|
||||
class Flake8(Command):
|
||||
|
||||
user_options = [('cov=', None, 'Run coverage'), ('cov-xml=', None, 'Generate junit xml report'), ('cov-html=',
|
||||
None, 'Generate junit html report'), ('junitxml=', None, 'Generate xml of test results')]
|
||||
user_options = []
|
||||
|
||||
def initialize_options(self):
|
||||
TestCommand.initialize_options(self)
|
||||
from flake8.main import application
|
||||
|
||||
self.flake8 = application.Application()
|
||||
self.flake8.initialize([])
|
||||
|
||||
def finalize_options(self):
|
||||
pass
|
||||
|
||||
def package_files(self):
|
||||
seen_package_directories = ()
|
||||
directories = self.distribution.package_dir or {}
|
||||
empty_directory_exists = "" in directories
|
||||
packages = self.distribution.packages or []
|
||||
for package in packages:
|
||||
if package in directories:
|
||||
package_directory = directories[package]
|
||||
elif empty_directory_exists:
|
||||
package_directory = os.path.join(directories[""], package)
|
||||
else:
|
||||
package_directory = package
|
||||
|
||||
if not package_directory.startswith(seen_package_directories):
|
||||
seen_package_directories += (package_directory + ".",)
|
||||
yield package_directory
|
||||
|
||||
def targets(self):
|
||||
return [package for package in self.package_files()] + ['tests', 'setup.py']
|
||||
|
||||
def run(self):
|
||||
self.flake8.run_checks(self.targets())
|
||||
self.flake8.formatter.start()
|
||||
self.flake8.report_errors()
|
||||
self.flake8.report_statistics()
|
||||
self.flake8.report_benchmarks()
|
||||
self.flake8.formatter.stop()
|
||||
try:
|
||||
self.flake8.exit()
|
||||
except SystemExit as e:
|
||||
# Cause system exit only if exit code is not zero (terminates
|
||||
# other possibly remaining/pending setuptools commands).
|
||||
if e.code:
|
||||
raise
|
||||
|
||||
|
||||
class PyTest(Command):
|
||||
|
||||
user_options = [('cov=', None, 'Run coverage'), ('cov-xml=', None, 'Generate junit xml report'),
|
||||
('cov-html=', None, 'Generate junit html report')]
|
||||
|
||||
def initialize_options(self):
|
||||
self.cov = []
|
||||
self.cov_xml = False
|
||||
self.cov_html = False
|
||||
self.junitxml = None
|
||||
|
||||
def finalize_options(self):
|
||||
TestCommand.finalize_options(self)
|
||||
if self.cov_xml or self.cov_html:
|
||||
self.cov = ['--cov', MAIN_PACKAGE, '--cov-report', 'term-missing']
|
||||
if self.cov_xml:
|
||||
self.cov.extend(['--cov-report', 'xml'])
|
||||
if self.cov_html:
|
||||
self.cov.extend(['--cov-report', 'html'])
|
||||
if self.junitxml is not None:
|
||||
self.junitxml = ['--junitxml', self.junitxml]
|
||||
|
||||
def run_tests(self):
|
||||
try:
|
||||
import pytest
|
||||
except:
|
||||
except Exception:
|
||||
raise RuntimeError('py.test is not installed, run: pip install pytest')
|
||||
params = {'args': self.test_args}
|
||||
if self.cov:
|
||||
params['args'] += self.cov
|
||||
if self.junitxml:
|
||||
params['args'] += self.junitxml
|
||||
params['args'] += ['--doctest-modules', MAIN_PACKAGE, '-vv']
|
||||
|
||||
import logging
|
||||
silence = logging.WARNING
|
||||
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=os.getenv('LOGLEVEL', silence))
|
||||
params['args'] += ['-s' if logging.getLogger().getEffectiveLevel() < silence else '--capture=fd']
|
||||
errno = pytest.main(**params)
|
||||
|
||||
args = ['--verbose', 'tests', '--doctest-modules', MAIN_PACKAGE] +\
|
||||
['-s' if logging.getLogger().getEffectiveLevel() < silence else '--capture=fd']
|
||||
if self.cov:
|
||||
args += self.cov
|
||||
|
||||
errno = pytest.main(args=args)
|
||||
sys.exit(errno)
|
||||
|
||||
|
||||
def get_install_requirements(path):
|
||||
content = open(os.path.join(__location__, path)).read()
|
||||
return [req for req in content.split('\n') if req != '']
|
||||
def run(self):
|
||||
from pkg_resources import evaluate_marker
|
||||
requirements = self.distribution.install_requires + ['mock>=2.0.0', 'pytest-cov', 'pytest'] +\
|
||||
[v for k, v in self.distribution.extras_require.items() if not k.startswith(':') or evaluate_marker(k[1:])]
|
||||
self.distribution.fetch_build_eggs(requirements)
|
||||
self.run_tests()
|
||||
|
||||
|
||||
def read(fname):
|
||||
return open(os.path.join(__location__, fname)).read()
|
||||
with open(os.path.join(__location__, fname)) as fd:
|
||||
return fd.read()
|
||||
|
||||
|
||||
def setup_package():
|
||||
def setup_package(version):
|
||||
# Assemble additional setup commands
|
||||
cmdclass = {}
|
||||
cmdclass['test'] = PyTest
|
||||
cmdclass = {'test': PyTest, 'flake8': Flake8}
|
||||
|
||||
# Some helper variables
|
||||
version = os.getenv('GO_PIPELINE_LABEL', VERSION)
|
||||
install_requires = []
|
||||
|
||||
install_reqs = get_install_requirements('requirements.txt')
|
||||
for r in read('requirements.txt').split('\n'):
|
||||
r = r.strip()
|
||||
if r == '':
|
||||
continue
|
||||
extra = False
|
||||
for e, v in EXTRAS_REQUIRE.items():
|
||||
if r.startswith(v[0]):
|
||||
EXTRAS_REQUIRE[e] = [r]
|
||||
extra = True
|
||||
if not extra:
|
||||
install_requires.append(r)
|
||||
|
||||
command_options = {'test': {'test_suite': ('setup.py', 'tests')}}
|
||||
if JUNIT_XML:
|
||||
command_options['test']['junitxml'] = 'setup.py', 'junit.xml'
|
||||
command_options = {'test': {}}
|
||||
if COVERAGE_XML:
|
||||
command_options['test']['cov_xml'] = 'setup.py', True
|
||||
if COVERAGE_HTML:
|
||||
@@ -142,17 +188,28 @@ def setup_package():
|
||||
keywords=KEYWORDS,
|
||||
long_description=read('README.rst'),
|
||||
classifiers=CLASSIFIERS,
|
||||
test_suite='tests',
|
||||
packages=find_packages(exclude=['tests', 'tests.*']),
|
||||
package_data={MAIN_PACKAGE: ["*.json"]},
|
||||
install_requires=install_reqs,
|
||||
setup_requires=['flake8'],
|
||||
python_requires='>=2.7',
|
||||
install_requires=install_requires,
|
||||
extras_require=EXTRAS_REQUIRE,
|
||||
setup_requires='flake8',
|
||||
cmdclass=cmdclass,
|
||||
tests_require=['mock>=2.0.0', 'pytest-cov', 'pytest'],
|
||||
command_options=command_options,
|
||||
entry_points={'console_scripts': CONSOLE_SCRIPTS},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
setup_package()
|
||||
old_modules = sys.modules.copy()
|
||||
try:
|
||||
from patroni import check_psycopg2, fatal, __version__
|
||||
finally:
|
||||
sys.modules.clear()
|
||||
sys.modules.update(old_modules)
|
||||
|
||||
if sys.version_info < (2, 7, 0):
|
||||
fatal('Patroni needs to be run with Python 2.7+')
|
||||
check_psycopg2()
|
||||
|
||||
setup_package(__version__)
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import os
|
||||
import shutil
|
||||
import unittest
|
||||
|
||||
from mock import Mock, patch
|
||||
|
||||
import psycopg2
|
||||
import urllib3
|
||||
|
||||
from patroni.dcs import Leader, Member
|
||||
from patroni.postgresql import Postgresql
|
||||
from patroni.postgresql.config import ConfigHandler
|
||||
from patroni.utils import RetryFailedError
|
||||
|
||||
|
||||
class SleepException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class MockResponse(object):
|
||||
|
||||
def __init__(self, status_code=200):
|
||||
self.status_code = status_code
|
||||
self.content = '{}'
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
return self.content.encode('utf-8')
|
||||
|
||||
@property
|
||||
def status(self):
|
||||
return self.status_code
|
||||
|
||||
@staticmethod
|
||||
def getheader(*args):
|
||||
return ''
|
||||
|
||||
|
||||
def requests_get(url, **kwargs):
|
||||
members = '[{"id":14855829450254237642,"peerURLs":["http://localhost:2380","http://localhost:7001"],' +\
|
||||
'"name":"default","clientURLs":["http://localhost:2379","http://localhost:4001"]}]'
|
||||
response = MockResponse()
|
||||
if url.startswith('http://local'):
|
||||
raise urllib3.exceptions.HTTPError()
|
||||
elif ':8011/patroni' in url:
|
||||
response.content = '{"role": "replica", "xlog": {"received_location": 0}, "tags": {}}'
|
||||
elif url.endswith('/members'):
|
||||
response.content = '[{}]' if url.startswith('http://error') else members
|
||||
elif url.startswith('http://exhibitor'):
|
||||
response.content = '{"servers":["127.0.0.1","127.0.0.2","127.0.0.3"],"port":2181}'
|
||||
elif url.endswith(':8011/reinitialize'):
|
||||
data = kwargs.get('data', '')
|
||||
if ' false}' in data:
|
||||
response.status_code = 503
|
||||
response.content = 'restarting after failure already in progress'
|
||||
else:
|
||||
response.status_code = 404
|
||||
return response
|
||||
|
||||
|
||||
class MockPostmaster(object):
|
||||
def __init__(self, is_running=True, is_single_master=False):
|
||||
self.is_running = Mock(return_value=is_running)
|
||||
self.is_single_master = Mock(return_value=is_single_master)
|
||||
self.wait_for_user_backends_to_close = Mock()
|
||||
self.signal_stop = Mock(return_value=None)
|
||||
self.wait = Mock()
|
||||
self.signal_kill = Mock(return_value=False)
|
||||
|
||||
|
||||
class MockCursor(object):
|
||||
|
||||
def __init__(self, connection):
|
||||
self.connection = connection
|
||||
self.closed = False
|
||||
self.rowcount = 0
|
||||
self.results = []
|
||||
self.description = [Mock()]
|
||||
|
||||
def execute(self, sql, *params):
|
||||
if sql.startswith('blabla'):
|
||||
raise psycopg2.ProgrammingError()
|
||||
elif sql == 'CHECKPOINT' or sql.startswith('SELECT pg_catalog.pg_create_'):
|
||||
raise psycopg2.OperationalError()
|
||||
elif sql.startswith('RetryFailedError'):
|
||||
raise RetryFailedError('retry')
|
||||
elif sql.startswith('SELECT slot_name'):
|
||||
self.results = [('blabla', 'physical'), ('foobar', 'physical'), ('ls', 'logical', 'a', 'b')]
|
||||
elif sql.startswith('SELECT CASE WHEN pg_catalog.pg_is_in_recovery()'):
|
||||
self.results = [(1, 2, 1, 0, False, 1, 1, None, None)]
|
||||
elif sql.startswith('SELECT pg_catalog.pg_is_in_recovery()'):
|
||||
self.results = [(False, 2)]
|
||||
elif sql.startswith('SELECT pg_catalog.to_char'):
|
||||
replication_info = '[{"application_name":"walreceiver","client_addr":"1.2.3.4",' +\
|
||||
'"state":"streaming","sync_state":"async","sync_priority":0}]'
|
||||
self.results = [('', 0, '', '', '', '', False, replication_info)]
|
||||
elif sql.startswith('SELECT name, setting'):
|
||||
self.results = [('wal_segment_size', '2048', '8kB', 'integer', 'internal'),
|
||||
('wal_block_size', '8192', None, 'integer', 'internal'),
|
||||
('shared_buffers', '16384', '8kB', 'integer', 'postmaster'),
|
||||
('wal_buffers', '-1', '8kB', 'integer', 'postmaster'),
|
||||
('search_path', 'public', None, 'string', 'user'),
|
||||
('port', '5433', None, 'integer', 'postmaster'),
|
||||
('listen_addresses', '*', None, 'string', 'postmaster'),
|
||||
('autovacuum', 'on', None, 'bool', 'sighup'),
|
||||
('unix_socket_directories', '/tmp', None, 'string', 'postmaster')]
|
||||
elif sql.startswith('IDENTIFY_SYSTEM'):
|
||||
self.results = [('1', 3, '0/402EEC0', '')]
|
||||
elif sql.startswith('TIMELINE_HISTORY '):
|
||||
self.results = [('', b'x\t0/40159C0\tno recovery target specified\n\n'
|
||||
b'1\t0/40159C0\tno recovery target specified\n\n'
|
||||
b'2\t0/402DD98\tno recovery target specified\n\n'
|
||||
b'3\t0/403DD98\tno recovery target specified\n')]
|
||||
else:
|
||||
self.results = [(None, None, None, None, None, None, None, None, None, None)]
|
||||
|
||||
def fetchone(self):
|
||||
return self.results[0]
|
||||
|
||||
def fetchall(self):
|
||||
return self.results
|
||||
|
||||
def __iter__(self):
|
||||
for i in self.results:
|
||||
yield i
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
class MockConnect(object):
|
||||
|
||||
server_version = 99999
|
||||
autocommit = False
|
||||
closed = 0
|
||||
|
||||
def cursor(self):
|
||||
return MockCursor(self)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def close():
|
||||
pass
|
||||
|
||||
|
||||
def psycopg2_connect(*args, **kwargs):
|
||||
return MockConnect()
|
||||
|
||||
|
||||
class PostgresInit(unittest.TestCase):
|
||||
_PARAMETERS = {'wal_level': 'hot_standby', 'max_replication_slots': 5, 'f.oo': 'bar',
|
||||
'search_path': 'public', 'hot_standby': 'on', 'max_wal_senders': 5,
|
||||
'wal_keep_segments': 8, 'wal_log_hints': 'on', 'max_locks_per_transaction': 64,
|
||||
'max_worker_processes': 8, 'max_connections': 100, 'max_prepared_transactions': 0,
|
||||
'track_commit_timestamp': 'off', 'unix_socket_directories': '/tmp', 'trigger_file': 'bla',
|
||||
'stats_temp_directory': '/tmp'}
|
||||
|
||||
@patch('psycopg2.connect', psycopg2_connect)
|
||||
@patch.object(ConfigHandler, 'write_postgresql_conf', Mock())
|
||||
@patch.object(ConfigHandler, 'replace_pg_hba', Mock())
|
||||
@patch.object(ConfigHandler, 'replace_pg_ident', Mock())
|
||||
@patch.object(Postgresql, 'get_postgres_role_from_data_directory', Mock(return_value='master'))
|
||||
def setUp(self):
|
||||
data_dir = os.path.join('data', 'test0')
|
||||
self.p = Postgresql({'name': 'postgresql0', 'scope': 'batman', 'data_dir': data_dir,
|
||||
'config_dir': data_dir, 'retry_timeout': 10,
|
||||
'krbsrvname': 'postgres', 'pgpass': os.path.join(data_dir, 'pgpass0'),
|
||||
'listen': '127.0.0.2, 127.0.0.3:5432', 'connect_address': '127.0.0.2:5432',
|
||||
'authentication': {'superuser': {'username': 'foo', 'password': 'test'},
|
||||
'replication': {'username': '', 'password': 'rep-pass'}},
|
||||
'remove_data_directory_on_rewind_failure': True,
|
||||
'use_pg_rewind': True, 'pg_ctl_timeout': 'bla',
|
||||
'parameters': self._PARAMETERS,
|
||||
'recovery_conf': {'foo': 'bar'},
|
||||
'pg_hba': ['host all all 0.0.0.0/0 md5'],
|
||||
'pg_ident': ['krb realm postgres'],
|
||||
'callbacks': {'on_start': 'true', 'on_stop': 'true', 'on_reload': 'true',
|
||||
'on_restart': 'true', 'on_role_change': 'true'}})
|
||||
|
||||
|
||||
class BaseTestPostgresql(PostgresInit):
|
||||
|
||||
def setUp(self):
|
||||
super(BaseTestPostgresql, self).setUp()
|
||||
|
||||
if not os.path.exists(self.p.data_dir):
|
||||
os.makedirs(self.p.data_dir)
|
||||
|
||||
self.leadermem = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres'})
|
||||
self.leader = Leader(-1, 28, self.leadermem)
|
||||
self.other = Member(0, 'test-1', 28, {'conn_url': 'postgres://replicator:[email protected]:5433/postgres',
|
||||
'tags': {'replicatefrom': 'leader'}})
|
||||
self.me = Member(0, 'test0', 28, {'conn_url': 'postgres://replicator:[email protected]:5434/postgres'})
|
||||
|
||||
def tearDown(self):
|
||||
if os.path.exists(self.p.data_dir):
|
||||
shutil.rmtree(self.p.data_dir)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user