Compare commits

...
55 Commits
Author SHA1 Message Date
Alexander KukushkinandGitHub fe23d1f2d0 Release 1.6.5 (#1503)
* bump version
* update release notes
* implement missing unit-tests and format code.
2020-04-23 16:02:01 +02:00
Feike SteenbergenandGitHub 8b860d7528 Skip missing values from pg_controldata (#1501)
Skip missing values from pg_controldata

When calling controldata(), it may return an empty dictionary, which in
turn caused the following error to occur:

    effective_configuration
        cvalue = parse_int(data[cname])
    KeyError: 'max_wal_senders setting'

Instead of causing a crash of this part, we now log the error and
continue.




This is the full output of the error:
```
2020-04-17 14:31:54,791 ERROR: Exception during execution of long running task restarting after failure
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/patroni/async_executor.py", line 97, in run
    wakeup = func(*args) if args else func()
  File "/usr/lib/python3/dist-packages/patroni/postgresql/__init__.py", line 707, in follow
    self.start(timeout=timeout, block_callbacks=change_role, role=role)
  File "/usr/lib/python3/dist-packages/patroni/postgresql/__init__.py", line 409, in start
    configuration = self.config.effective_configuration
  File "/usr/lib/python3/dist-packages/patroni/postgresql/config.py", line 983, in effective_configuration
    cvalue = parse_int(data[cname])
KeyError: 'max_wal_senders setting'
```
2020-04-23 12:51:38 +02:00
Alexander KukushkinandGitHub be4c078d95 Etcd smart refresh members (#1499)
In dynamic environments it is common that during the rolling upgrade etcd nodes are changing their IP addresses. If the etcd node where Patroni is currently connected to is upgraded last, it could happen that the cached topology doesn't contain any live node anymore and therefore request can't be retried and totally fails, usually resulting in demoting of the primary.

In order to partially overcome the problem, Patroni is already doing a periodic (every 5 minutes) rediscovery of the etcd cluster topology, but in case of very fast node rotation there was still a possibility to hit the issue.

This PR is an attempt to address the problem. If the list of nodes exhausted, Patroni will try to perform initial discovery via an external mechanism, like resolving A or SRV dns records and if the new list is different from the original, Patroni will use it as the new etcd cluster topology.

In order to deal with tcp issues the connect_timeout is set to max(read_timeout/2, 1). It will make list of members exhaust faster, but leaves the time to perform topology rediscovery and another attempt.

The third issue addressed by this PR - it could happen that dns names of etcd nodes didn't change, but ip addresses are new, therefore we clean up the internal dns cache when doing topology rediscovery.

Besides that, this commit makes `_machines_cache` property pretty much static, it will be updated only when the topology has changed and helps to avoid concurrency issues.
2020-04-23 12:51:05 +02:00
Alexander KukushkinandGitHub 80fbe90056 Issue CHEKPOINT explicitely after promote happened (#1498)
It is safe to call pg_rewind on the replica only when pg_control on the primary contains information about the latest timeline. Postgres is usually doing immediate checkpoint right after promote and in most cases it works just fine. Unfortunately we regularly receive complaints that it takes to long (minutes) until the checkpoint is done and replicas can't perform rewind. At the same time doing the checkpoint manually immediately helped. So Patroni starts doing the same. When the promotion happened and postgres is not running in recovery, we explicitly issue the checkpoint.

We are intentionally not using the AsyncExecutor here, because we want the HA loop continues doing its normal flow.
2020-04-20 11:55:05 +02:00
ksarabu1andGitHub 5fa912f8fa Make max history timelines in DCS configurable (#1491)
Close https://github.com/zalando/patroni/issues/1487
2020-04-17 16:27:38 +02:00
ksarabu1andGitHub fc962121d7 Reinitialize Bug fix with user defined tablespaces (#1494)
During reinit, Patroni removing pgdata and leaving user-defined tablespace directory. This is causing Patroni to loop in reinit.
2020-04-17 07:49:55 +02:00
Alexander KukushkinandGitHub 337f9efc9e Improve patronictl list output (#1486)
The redundant column `Column` will be presented in the table header.

Depending on output format `Tags` are serialized differently:
* For *pretty* format YAML is used, every element on the new line
* For *tsv* format for YAML is also used, but all elements and on the same line (similar to JSON)
* For *json* and *yaml* formats `Tags` are serialized into an appropriate format.

<details><summary>Examples of output in pretty formats:</summary>

```bash
$ patronictl list
+ Cluster: batman (6813309862653668387) +---------+----+-----------+---------------------+
|    Member   |      Host      |  Role  |  State  | TL | Lag in MB | Tags                |
+-------------+----------------+--------+---------+----+-----------+---------------------+
| postgresql0 | 127.0.0.1:5432 | Leader | running |  3 |           | clonefrom: true     |
|             |                |        |         |    |           | noloadbalance: true |
|             |                |        |         |    |           | nosync: true        |
+-------------+----------------+--------+---------+----+-----------+---------------------+
| postgresql1 | 127.0.0.1:5433 |        | running |  3 |       0.0 |                     |
+-------------+----------------+--------+---------+----+-----------+---------------------+

$ patronictl list badclustername
+ Cluster: badclustername (uninitialized) ------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+------+------+-------+----+-----------+
+--------+------+------+-------+----+-----------+
```
</details>

<details><summary>Example in tsv format:</summary>

```bash
Cluster Member  Host    Role    State   TL      Lag in MB       Pending restart Tags
batman  postgresql0     127.0.0.1:5432  Leader  running 2
batman  postgresql1     127.0.0.1:5433          running 2       0               {clonefrom: true, nofailover: true, noloadbalance: true, replicatefrom: postgresql0}
batman  postgresql2     127.0.0.1:5434          running 2       0       *       {replicatefrom: postgres1}
```
</details>

In addition to that, `patronictl list` command will stop showing keys with empty values in `json` and `yaml` formats.
<details><summary>Examples:</summary>

```yaml
$ patronictl list -f yaml
- Cluster: batman
  Host: 127.0.0.1:5432
  Member: postgresql0
  Role: Leader
  State: running
  TL: 2
- Cluster: batman
  Host: 127.0.0.1:5433
  Lag in MB: 0
  Member: postgresql1
  State: running
  TL: 2
  Tags:
    clonefrom: true
    nofailover: true
    noloadbalance: true
    replicatefrom: postgresql0
- Cluster: batman
  Host: 127.0.0.1:5434
  Lag in MB: 0
  Member: postgresql2
  Pending restart: '*'
  State: running
  TL: 2
  Tags:
    replicatefrom: postgres1
```

```json
$ patronictl list -f json | jq .
[
  {
    "Cluster": "batman",
    "Member": "postgresql0",
    "Host": "127.0.0.1:5432",
    "Role": "Leader",
    "State": "running",
    "TL": 2
  },
  {
    "Cluster": "batman",
    "Member": "postgresql1",
    "Host": "127.0.0.1:5433",
    "State": "running",
    "TL": 2,
    "Lag in MB": 0,
    "Tags": {
      "nofailover": true,
      "noloadbalance": true,
      "replicatefrom": "postgresql0",
      "clonefrom": true
    }
  },
  {
    "Cluster": "batman",
    "Member": "postgresql2",
    "Host": "127.0.0.1:5434",
    "State": "running",
    "TL": 2,
    "Lag in MB": 0,
    "Pending restart": "*",
    "Tags": {
      "replicatefrom": "postgres1"
    }
  }
]
```
</details>
2020-04-15 12:19:18 +02:00
ksarabu1andGitHub e3335bea1a Master stop timeout (#1445)
## Feature: Postgres stop timeout

Switchover/Failover operation hangs on signal_stop (or checkpoint) call when postmaster doesn't respond or  hangs for some reason(Issue described in [1371](https://github.com/zalando/patroni/issues/1371)). This is leading to service loss for an extended period of time until the hung postmaster starts responding or it is killed by some other actor.

### 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.
2020-04-15 12:18:49 +02:00
Alexander KukushkinandGitHub 27cda08ece Improve unit-tests (#1479)
* tests were failing on windows and macos
* improve coverage
2020-04-09 10:34:35 +02:00
Alexander KukushkinandGitHub 369a93ce2a Handle cases when conn_url is not defined (#1482)
On K8s when one of the Patroni pods in starting there is valid annotation yet, which could cause failure in patronictl.
In addition to that handle cases if port isn't specified in the standby_cluster configuration.

Close https://github.com/zalando/patroni/issues/1100
Close https://github.com/zalando/patroni/issues/1463
2020-04-09 10:34:12 +02:00
Alexander KukushkinandGitHub e58680f833 Convert recovery_min_apply_delay to ms before doing comparison (#1484)
Fixes https://github.com/zalando/patroni/issues/1483
2020-04-09 10:33:38 +02:00
Kaarel MoppelandGitHub d58006319b Patronictl - fail if a config file is specified explicitly but not found (#1467)
$ python3 patronictl.py -c postgresql0.yml list
Error: Provided config file postgresql0.yml not existing or no read rights. Check the -c/--config-file parameter
2020-04-01 15:52:43 +02:00
Kaarel MoppelandGitHub 92d74af06e Better patronictl help text for the "flush" subcommand (#1466)
Right now it's not really clear from --help what it does, flushing in software
context usually means persisting...so actually it's the opposite, so make
the intention more explicit.
2020-04-01 15:51:50 +02:00
0m1xaandGitHub 80354f6484 Update Dockerfile (#1461)
On postgres:12 find command without this pattern deletes file i18n_ctype which is needed by localdef. And localedef exit with code !=0
2020-04-01 15:51:19 +02:00
Casey Allen ShobeandGitHub 0e4d7f01f2 Correct documentation for consul.host (#1438)
Close #1434
2020-04-01 15:50:50 +02:00
Danyal ProutandGitHub 810c179592 Kazoo 2.7.0 Compatibility
Close https://github.com/zalando/patroni/issues/1448
2020-03-18 11:04:09 +01:00
Alexander KukushkinandGitHub d2080a3116 Retry if the retry-after http header is set (#1431)
If the K8s API is overwhelmed with requests it might ask to retry.
2020-03-13 16:36:39 +01:00
Alexander KukushkinandGitHub d82301688f Fix pyinstaller compatibility (#1441)
Close https://github.com/zalando/patroni/issues/1440
2020-03-13 16:36:12 +01:00
Feike SteenbergenandGitHub d74a4b23a6 Scrub KUBERNETES_ environment from the postmaster (#1407)
The KUBERNETES_ environment variables are not required for PostgreSQL, yet having them exposed to the postmaster will also expose them to backends and to regular database users (using pl/perl for example).
2020-03-10 12:08:29 +01:00
Michail NikolaevandGitHub 795efc4548 Note about possible data loss while canceling postgres backends. (#1414)
Note about possible data loss while canceling postgres backends.

Related to zalando#1412
2020-03-10 12:08:01 +01:00
Alexander KukushkinandGitHub b020874486 Small improvement in tests (#1423)
which actually revealed a small issue in the validator
2020-03-10 12:07:40 +01:00
Alexander KukushkinandGitHub ab38ab2e97 Apply 1 second backoff if LIST failed (#1424)
It is mostly necessary to avoid flooding logs, but also help to prevent starvation of the main thread.
2020-03-10 12:07:26 +01:00
Alexander KukushkinandGitHub 613634c26b Reset rewind state if postgres started after successful pg_rewind (#1408)
Close https://github.com/zalando/patroni/issues/1406
2020-02-27 12:24:17 +01:00
Alexander KukushkinandGitHub 4a29caa9d3 On role change callback didn't fire on failed primary (#1420)
Bug was introduced in https://github.com/zalando/patroni/pull/703
Close https://github.com/zalando/patroni/issues/1418
2020-02-27 12:22:44 +01:00
Alexander KukushkinandGitHub bcd75bbeeb Avoid opening replication connection on every cycle of HA loop (#1422)
Bug was introduces in the https://github.com/zalando/patroni/pull/1332
2020-02-27 12:22:11 +01:00
Steven De CoeyerandGitHub 0fa70e8d88 Updates README (#1394)
We need to ensure to enable etcd v2, cfr. https://github.com/zalando/patroni/issues/1270 and https://github.com/zalando/patroni/issues/1163.
2020-02-20 10:15:58 +01:00
damien clochardandGitHub e759a3f2ef [doc] add PATRONICTL_CONFIG_FILE env var (#1397) 2020-02-20 10:14:36 +01:00
Julien RiouandGitHub 7b0e012f62 Disable SSL verification for Consul when it is required (#1399)
Consul client uses urllib3 with a verify=True by default. When
SSL verification is disabled with verify=False, we can see
CERTIFICATE_VERIFY_FAILED exceptions. With urllib3 1.19.1-1 on
Debian Stretch, the "cert_reqs" argument  must be explicitaly set
to ssl.CERT_NONE to effectively disable SSL verification.
2020-02-20 10:13:41 +01:00
Alexander KukushkinandGitHub 80ce61876e Don't create permanent physical slot with name of the primary (#1392)
It is a regular issue that primary is recycling WALs when one of the replicas is down for a long time. So far there were only two solutions for such a problem and both of them are not perfect:
1. Increase `wal_keep_segments`, but it is hard to guess the good value.
2. Use continuous archiving and PITR, but it is not always possible.

This PR is introducing the way to solve the problem for static clusters, with a fixed number of nodes and names that never change. You just need to list the names of all nodes in the `slots` so the primary will not remove the slot when the node is down (not registered in DCS).
Of course, the primary will not create the permanent slot which is matching its own name.

Usage example: let's assume you have a cluster with nodes named *abc1*, *abc2*, and *abc3*.
You have to run `patronictl edit-config` and put the following snippet into the configuration:
```yaml
slots:
  abc1:
    type: physical
  abc2:
    type: physical
  abc3:
    type: physical
```

If the node *abc2* is the primary, it will always create slots for *abc1* and *abc3* even if they are not running, but will not create slot *abc2*.
Other nodes will behave the same.

Close #280
2020-02-20 10:07:43 +01:00
Igor YanchenkoandGitHub ffde403a0a Config validator implemented (#1314) 2020-02-20 09:40:44 +01:00
Paul VossandGitHub 7e17092809 Fix permissions for openshift block devices (#1361)
OpenShift enforces securityContext.fsGroups for block devices and sets group stickybits for volumeMounts.

This leads to patroni pods failing to start after the first restart:
> 2020-01-13 14:46:13.695 UTC [143] FATAL:  data directory "/home/postgres/pgdata/pgroot/data" has invalid permissions
2020-01-13 14:46:13.695 UTC [143] DETAIL:  Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).

A initContainer which fixes the OpenShift tampering solves the issue. I stole the solution from the stable postgres helm chart:
https://github.com/helm/charts/pull/14540/files

Tested on OpenShift v3.11

Note: This error does not occur when using shared filesystems (like NFS)
2020-02-13 15:07:56 +01:00
Kostiantyn NemchenkoandGitHub bc948ce551 Show tags for member via patronictl (#1383)
Add one more field to patronictl output to check tags defined for a member.
Closes #1375
2020-02-13 15:07:05 +01:00
Michael BanckandGitHub f419d73465 Set postgresql.pgpass to ./pgpass (#1386)
This avoids test failures if $HOME is not available (fixes: #1385).
2020-02-13 15:06:36 +01:00
Alexander KukushkinandGitHub 4737af48bf Get rid of dependency on tzlocal module (#1390)
It was used only to add the local timezone to the datetime specified in the patronictl for scheduled switchover or restart.
The `dateutil.tz.tzlocal()` does the same job equally well.
2020-02-13 14:49:57 +01:00
Alexander KukushkinandGitHub dc1966e3bc Release 1.6.4 (#1380)
* Bump version
* Update release notes
2020-01-27 14:15:21 +01:00
Alexander KukushkinandGitHub 6aa3f809d4 Configure keepalive for connections to K8s API (#1366)
In case if we got nothing from the socket after the TTL seconds it should be considered dead.
2020-01-27 09:25:08 +01:00
Alexander KukushkinandGitHub 902411239f More compatibility with windows (#1367)
* unix-domain sockets are not yet supported
* signal.SIGQUIT doesn't exists
2020-01-24 12:52:55 +01:00
Alexander KukushkinandGitHub 0eb1e0568b Compatibility with python 3.7.6 (#1368)
The urlparse function has changed.

Old versions:
```python
>>> urlparse('localhost:8500')
ParseResult(scheme='', netloc='', path='localhost:8500', params='', query='', fragment='')
```

3.7.6:
```python
>>> urlparse('localhost:8500')
ParseResult(scheme='localhost', netloc='', path='8500', params='', query='', fragment='')
```
2020-01-24 12:52:34 +01:00
Alexander KukushkinandGitHub 27ff9dfda3 Avoid logging passwords on user creation (#1370)
Fixes https://github.com/zalando/patroni/issues/1365
2020-01-24 10:52:23 +01:00
Igor YanchenkoandAlexander Kukushkin 16fe180ed6 implemented stop signal using pg_ctl for non posix systems (#1342)
Using pg_ctl to send stop signal for non posix os.
2020-01-16 14:35:47 +01:00
Alexander KukushkinandGitHub 1c4d395d5a Handle exception from Ha.shutdown (#1351)
During the shutdown Patroni is trying to update its status in the DCS.
If the DCS is inaccessible an exception might be raised. Lack of exception handling prevents logger thread from stopping.

Fixes https://github.com/zalando/patroni/issues/1344
2020-01-16 14:34:58 +01:00
Alexander KukushkinandGitHub c5fc6fd936 Special handling of parameters with period (#1349)
It might be that they are defined by the extension and therefore the unit is not necessarily is the string.
It also could be that change of the value requires a restart (for example pg_stat_statements.max).
2020-01-16 14:34:31 +01:00
Alexander KukushkinandGitHub 1461d7d4b8 Allow certain recovery parameters be defined in the custom_conf (#1335)
Fixes https://github.com/zalando/patroni/issues/1333
2020-01-15 12:41:07 +01:00
Igor YanchenkoandAlexander Kukushkin ea76a40845 Make sure postgresql.pgpass is a file or it does not exist (#1337)
Also make sure that it is located in the writable directory.
2020-01-15 12:40:41 +01:00
Alexander KukushkinandGitHub 102a12ea5a Catch all exceptions when calling socket.getaddrinfo (#1355)
it serves two purposes:
1. We don't want accidentally break the thread
2. During the shutdown socket.gaierror become unresolvable and nasty exceptions are raised

Close: https://github.com/zalando/patroni/issues/1353
2020-01-15 12:38:34 +01:00
Alexander KukushkinandGitHub 9e8ae95bce Finally fix a problem with case sensitivity of sync standby names (#1359)
Close https://github.com/zalando/patroni/issues/1358
2020-01-15 12:38:05 +01:00
Kostiantyn NemchenkoandAlexander Kukushkin a2a5cc2f71 Disable serfHealth Consul check (#1364)
Fixes #1362 and #1363.
2020-01-15 12:37:35 +01:00
Alexander KukushkinandGitHub 16d1ffdde7 Update timeline on standby cluster (#1332)
Fixes https://github.com/zalando/patroni/issues/1031
2019-12-20 12:56:00 +01:00
Alexander KukushkinandGitHub a675fa18dc Handle case when replication password is set to null (#1330)
Fixes https://github.com/zalando/patroni/issues/1231
2019-12-20 12:06:18 +01:00
Igor YanchenkoandAlexander Kukushkin 26b6e00575 wait option for patronictl reinit implemented (#1339)
Wait to finish `reinit` if `--wait` option is used.
Every 2 seconds it pulls the status from Patroni REST API and reports to console.
2019-12-20 12:05:39 +01:00
Alexander KukushkinandGitHub d941f6bc5e Use restore_command from standby_cluster config on cascading replicas (#1341)
The standby_leader was already doing it from the beginning feature existed. Not doing the same on replicas might prevent them from catching up with standby leader due to WALs being recycled.

In addition to that apply the same strategy to archive_cleanup_command.
2019-12-20 12:03:25 +01:00
Igor YanchenkoandAlexander Kukushkin 7ff27d9e10 Make sure unix_socket_directories and stats_temp_directory exist (#1293)
Upon the start of Patroni and Postgres make sure that unix_socket_directories and stats_temp_directory exist or try to create them. Patroni will exit if failed to create them.

Close https://github.com/zalando/patroni/issues/863
2019-12-11 12:26:17 +01:00
Igor YanchenkoandAlexander Kukushkin 2174d66f97 Rewriten shell scripts in python to make them compatible with windows (#1326) 2019-12-11 12:07:05 +01:00
Pavlo GolubandAlexander Kukushkin 919e9c54d2 Make dest argument default value of backup() cross platform (#1324)
Fixes #1325
2019-12-11 11:25:41 +01:00
Alexander KukushkinandGitHub 08d6e5e50e BUGFIX: don't leak password when running pg_rewind (#1321)
In addition to that:
* enforce security settings from `postgresql.authention`
* update release notes
* bump version
* close https://github.com/zalando/patroni/issues/1320
2019-12-05 18:19:38 +01:00
51 changed files with 1821 additions and 434 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ addons:
- expect-dev # for unbuffer - expect-dev # for unbuffer
env: env:
global: global:
- ETCDVERSION=3.0.17 ZKVERSION=3.4.11 CONSULVERSION=0.7.4 - ETCDVERSION=3.0.17 ZKVERSION=3.4.14 CONSULVERSION=0.7.4
- PYVERSIONS="2.7 3.5 3.6" - PYVERSIONS="2.7 3.5 3.6"
- EXCLUDE_BEHAVE="3.5" - EXCLUDE_BEHAVE="3.5"
- BOTO_CONFIG=/doesnotexist - BOTO_CONFIG=/doesnotexist
+1 -1
View File
@@ -30,7 +30,7 @@ RUN set -ex \
\ \
# Cleanup all locales but en_US.UTF-8 # Cleanup all locales but en_US.UTF-8
&& find /usr/share/i18n/charmaps/ -type f ! -name UTF-8.gz -delete \ && 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 \ && 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 \ && echo 'en_US.UTF-8 UTF-8' > /usr/share/i18n/SUPPORTED \
\ \
# Make sure we have a en_US.UTF-8 locale available # Make sure we have a en_US.UTF-8 locale available
+4 -3
View File
@@ -35,8 +35,8 @@ Example: defining ``PATRONI_admin_PASSWORD=strongpasswd`` and ``PATRONI_admin_OP
Consul 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, in format: http(s)://host:port - **PATRONI\_CONSUL\_URL**: url for the Consul local agent, in format: http(s)://host:port
- **PATRONI\_CONSUL\_PORT**: (optional) Consul port - **PATRONI\_CONSUL\_PORT**: (optional) Consul port
- **PATRONI\_CONSUL\_SCHEME**: (optional) **http** or **https**, defaults to **http** - **PATRONI\_CONSUL\_SCHEME**: (optional) **http** or **https**, defaults to **http**
- **PATRONI\_CONSUL\_TOKEN**: (optional) ACL token - **PATRONI\_CONSUL\_TOKEN**: (optional) ACL token
@@ -46,7 +46,7 @@ Consul
- **PATRONI\_CONSUL\_KEY**: (optional) File with the client key. Can be empty if the key is part of 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\_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\_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. If not specified Consul will use "serfHealth" in additional to the TTL based check created by Patroni. Additional checks, in particular the "serfHealth", may cause the leader lock to expire faster than in `ttl` seconds when the leader instance becomes unavailable. - **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\_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 - **PATRONI\_CONSUL\_SERVICE\_CHECK\_INTERVAL**: (optional) how often to perform health check against registered url
@@ -130,6 +130,7 @@ REST API
CTL CTL
--- ---
- **PATRONICTL\_CONFIG\_FILE**: location of the configuration file.
- **PATRONI\_CTL\_INSECURE**: Allow connections to REST API without verifying SSL certs. - **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\_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\_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.
+1 -1
View File
@@ -107,7 +107,7 @@ obtain those files from the git repository and replace `./patroni.py` below with
To get started, do the following from different terminals: 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 postgres0.yml
> ./patroni.py postgres1.yml > ./patroni.py postgres1.yml
+17 -15
View File
@@ -15,12 +15,14 @@ Dynamic configuration is stored in the DCS (Distributed Configuration Store) and
- **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 - **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 - **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. - **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\_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**: 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. - **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**: - **postgresql**:
- **use\_pg\_rewind**: whether or not to use pg_rewind. Defaults to `false`. - **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+. - **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. - **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. - **parameters**: list of configuration settings for Postgres.
- **standby\_cluster**: if this section is defined, we want to bootstrap a standby cluster. - **standby\_cluster**: if this section is defined, we want to bootstrap a standby cluster.
@@ -32,7 +34,7 @@ Dynamic configuration is stored in the DCS (Distributed Configuration Store) and
- **archive\_cleanup\_command**: cleanup command for standby leader - **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 - **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. - **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. It 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. - **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``. - **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. - **database**: the database name where logical slots should be created.
- **plugin**: the plugin name for the logical slot. - **plugin**: the plugin name for the logical slot.
@@ -87,20 +89,20 @@ Consul
------ ------
Most of the parameters are optional, but you have to specify one of the **host** or **url** Most of the parameters are optional, but you have to specify one of the **host** or **url**
- **host**: the host:port for the Consul endpoint, in format: http(s)://host:port - **host**: the host:port for the Consul local agent.
- **url**: url for the Consul endpoint - **url**: url for the Consul local agent, in format: http(s)://host:port.
- **port**: (optional) Consul port - **port**: (optional) Consul port.
- **scheme**: (optional) **http** or **https**, defaults to **http** - **scheme**: (optional) **http** or **https**, defaults to **http**.
- **token**: (optional) ACL token - **token**: (optional) ACL token.
- **verify**: (optional) whether to verify the SSL certificate for HTTPS requests - **verify**: (optional) whether to verify the SSL certificate for HTTPS requests.
- **cacert**: (optional) The ca certificate. If present it will enable validation. - **cacert**: (optional) The ca certificate. If present it will enable validation.
- **cert**: (optional) file with the client certificate - **cert**: (optional) file with the client certificate.
- **key**: (optional) file with the client key. Can be empty if the key is part of **cert**. - **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. - **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/>`__) - **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. If not specified Consul will use "serfHealth" in additional to the TTL based check created by Patroni. Additional checks, in particular the "serfHealth", may cause the leader lock to expire faster than in `ttl` seconds when the leader instance becomes unavailable - **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** - **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 - **service\_check\_interval**: (optional) how often to perform health check against registered url.
Etcd Etcd
---- ----
@@ -109,8 +111,8 @@ Most of the parameters are optional, but you have to specify one of the **host**
- **host**: the host:port for the etcd endpoint. - **host**: the host:port for the etcd endpoint.
- **hosts**: list of etcd endpoint in format host1:port1,host2:port2,etc... Could be a comma separated string or an actual yaml list. - **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. - **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 - **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** - **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. - **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. - **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.
@@ -126,7 +128,7 @@ ZooKeeper
Exhibitor Exhibitor
--------- ---------
- **hosts**: initial list of Exhibitor (ZooKeeper) nodes in format: 'host1,host2,etc...'. This list updates automatically whenever the Exhibitor (ZooKeeper) cluster topology changes. - **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. - **port**: Exhibitor port.
.. _kubernetes_settings: .. _kubernetes_settings:
+1
View File
@@ -76,6 +76,7 @@ Also, the following Patroni configuration options can be changed only dynamicall
- loop_wait: 10 - loop_wait: 10
- retry_timeouts: 10 - retry_timeouts: 10
- maximum_lag_on_failover: 1048576 - maximum_lag_on_failover: 1048576
- max_timelines_history: 0
- check_timeline: false - check_timeline: false
- postgresql.use_slots: true - postgresql.use_slots: true
+192
View File
@@ -3,6 +3,198 @@
Release notes Release notes
============= =============
Version 1.6.5
-------------
**New features**
- Master stop timeout (Krishna Sarabu)
The number of seconds Patroni is allowed to wait when stopping Postgres. Effective only when ``synchronous_mode`` is enabled. When set to value greater than 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 to non-positive value, ``master_stop_timeout`` does not have an effect.
- Don't create permanent physical slot with name of the primary (Alexander Kukushkin)
It is a common problem that the primary recycles WAL segments while the replica is down. Now we have a good solution for static clusters, with a fixed number of nodes and names that never change. You just need to list the names of all nodes in the ``slots`` so the primary will not remove the slot when the node is down (not registered in DCS).
- First draft of Config Validator (Igor Yanchenko)
Use ``patroni --validate-config patroni.yaml`` in order to validate Patroni configuration.
- Possibility to configure max length of timelines history (Krishna)
Patroni writes the history of failovers/switchovers into the ``/history`` key in DCS. Over time the size of this key becomes big, but in most cases only the last few lines are interesting. The ``max_timelines_history`` parameter allows to specify the maximum number of timeline history items to be kept in DCS.
- Kazoo 2.7.0 compatibility (Danyal Prout)
Some non-public methods in Kazoo changed their signatures, but Patroni was relying on them.
**Improvements in patronictl**
- Show member tags (Kostiantyn Nemchenko, Alexander)
Tags are configured individually for every node and there was no easy way to get an overview of them
- Improve members output (Alexander)
The redundant cluster name won't be shown anymore on every line, only in the table header.
.. code-block:: bash
$ patronictl list
+ Cluster: batman (6813309862653668387) +---------+----+-----------+---------------------+
| Member | Host | Role | State | TL | Lag in MB | Tags |
+-------------+----------------+--------+---------+----+-----------+---------------------+
| postgresql0 | 127.0.0.1:5432 | Leader | running | 3 | | clonefrom: true |
| | | | | | | noloadbalance: true |
| | | | | | | nosync: true |
+-------------+----------------+--------+---------+----+-----------+---------------------+
| postgresql1 | 127.0.0.1:5433 | | running | 3 | 0.0 | |
+-------------+----------------+--------+---------+----+-----------+---------------------+
- Fail if a config file is specified explicitly but not found (Kaarel Moppel)
Previously ``patronictl`` was only reporting a ``DEBUG`` message.
- Solved the problem of not initialized K8s pod breaking patronictl (Alexander)
Patroni is relying on certain pod annotations on K8s. When one of the Patroni pods is stopping or starting there is no valid annotation yet and ``patronictl`` was failing with an exception.
**Stability improvements**
- Apply 1 second backoff if LIST call to K8s API server failed (Alexander)
It is mostly necessary to avoid flooding logs, but also helps to prevent starvation of the main thread.
- Retry if the ``retry-after`` HTTP header is returned by K8s API (Alexander)
If the K8s API server is overwhelmed with requests it might ask to retry.
- Scrub ``KUBERNETES_`` environment from the postmaster (Feike Steenbergen)
The ``KUBERNETES_`` environment variables are not required for PostgreSQL, yet having them exposed to the postmaster will also expose them to backends and to regular database users (using pl/perl for example).
- Clean up tablespaces on reinitialize (Krishna)
During reinit, Patroni was removing only ``PGDATA`` and leaving user-defined tablespace directories. This is causing Patroni to loop in reinit. The previous workarond for the problem was implementing the :ref:`custom bootstrap <custom_bootstrap>` script.
- Explicitly execute ``CHECKPOINT`` after promote happened (Alexander)
It helps to reduce the time before the new primary is usable for ``pg_rewind``.
- Smart refresh of Etcd members (Alexander)
In case Patroni failed to execute a request on all members of the Etcd cluster, Patroni will re-check ``A`` or ``SRV`` records for changes of IPs/hosts before retrying the next time.
- Skip missing values from ``pg_controldata`` (Feike)
Values are missing when trying to use binaries of a version that doesn't match PGDATA. Patroni will try to start Postgres anyway, and Postgres will complain that the major version doesn't match and abort with an error.
**Bugfixes**
- Disable SSL verification for Consul when required (Julien Riou)
Starting from a certain version of ``urllib3``, the ``cert_reqs`` must be explicitly set to ``ssl.CERT_NONE`` in order to effectively disable SSL verification.
- Avoid opening replication connection on every cycle of HA loop (Alexander)
Regression was introduced in 1.6.4.
- Call ``on_role_change`` callback on failed primary (Alexander)
In certain cases it could lead to the virtual IP remaining attached to the old primary. Regression was introduced in 1.4.5.
- Reset rewind state if postgres started after successful pg_rewind (Alexander)
As a result of this bug Patroni was starting up manually shut down postgres in the pause mode.
- Convert ``recovery_min_apply_delay`` to ``ms`` when checking ``recovery.conf``
Patroni was indefinitely restarting replica if ``recovery_min_apply_delay`` was configured on PostgreSQL older than 12.
- PyInstaller compatibility (Alexander)
PyInstaller freezes (packages) Python applications into stand-alone executables. The compatibility was broken when we switched to the ``spawn`` method instead of ``fork`` for ``multiprocessing``.
Version 1.6.4
-------------
**New features**
- Implemented ``--wait`` option for ``patronictl reinit`` (Igor Yanchenko)
Patronictl will wait for ``reinit`` to finish is the ``--wait`` option is used.
- Further improvements of Windows support (Igor Yanchenko, Alexander Kukushkin)
1. All shell scripts which are used for integration testing are rewritten in python
2. The ``pg_ctl kill`` will be used to stop postgres on non posix systems
3. Don't try to use unix-domain sockets
**Stability improvements**
- Make sure ``unix_socket_directories`` and ``stats_temp_directory`` exist (Igor)
Upon the start of Patroni and Postgres make sure that ``unix_socket_directories`` and ``stats_temp_directory`` exist or try to create them. Patroni will exit if failed to create them.
- Make sure ``postgresql.pgpass`` is located in the place where Patroni has write access (Igor)
In case if it doesn't have a write access Patroni will exit with exception.
- Disable Consul ``serfHealth`` check by default (Kostiantyn Nemchenko)
Even in case of little network problems the failing ``serfHealth`` leads to invalidation of all sessions associated with the node. Therefore, the leader key is lost much earlier than ``ttl`` which causes unwanted restarts of replicas and maybe demotion of the primary.
- Configure tcp keepalives for connections to K8s API (Alexander)
In case if we get nothing from the socket after TTL seconds it can be considered dead.
- Avoid logging of passwords on user creation (Alexander)
If the password is rejected or logging is configured to verbose or not configured at all it might happen that the password is written into postgres logs. In order to avoid it Patroni will change ``log_statement``, ``log_min_duration_statement``, and ``log_min_error_statement`` to some safe values before doing the attempt to create/update user.
**Bugfixes**
- Use ``restore_command`` from the ``standby_cluster`` config on cascading replicas (Alexander)
The ``standby_leader`` was already doing it from the beginning the feature existed. Not doing the same on replicas might prevent them from catching up with standby leader.
- Update timeline reported by the standby cluster (Alexander)
In case of timeline switch the standby cluster was correctly replicating from the primary but ``patronictl`` was reporting the old timeline.
- Allow certain recovery parameters be defined in the custom_conf (Alexander)
When doing validation of recovery parameters on replica Patroni will skip ``archive_cleanup_command``, ``promote_trigger_file``, ``recovery_end_command``, ``recovery_min_apply_delay``, and ``restore_command`` if they are not defined in the patroni config but in files other than ``postgresql.auto.conf`` or ``postgresql.conf``.
- Improve handling of postgresql parameters with period in its name (Alexander)
Such parameters could be defined by extensions where the unit is not necessarily a string. Changing the value might require a restart (for example ``pg_stat_statements.max``).
- Improve exception handling during shutdown (Alexander)
During shutdown Patroni is trying to update its status in the DCS. If the DCS is inaccessible an exception might be raised. Lack of exception handling was preventing logger thread from stopping.
Version 1.6.3
-------------
**Bugfixes**
- Don't expose password when running ``pg_rewind`` (Alexander Kukushkin)
Bug was introduced in the `#1301 <https://github.com/zalando/patroni/pull/1301>`__
- Apply connection parameters specified in the ``postgresql.authentication`` to ``pg_basebackup`` and custom replica creation methods (Alexander)
They were relying on url-like connection string and therefore parameters never applied.
Version 1.6.2 Version 1.6.2
------------- -------------
+2
View File
@@ -57,6 +57,8 @@ You can ensure that a standby never becomes the synchronous standby by setting `
Synchronous mode can be switched on and off via Patroni REST interface. See :ref:`dynamic configuration <dynamic_configuration>` 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 Synchronous mode implementation
------------------------------- -------------------------------
+21
View File
@@ -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)
+14
View File
@@ -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))
-22
View File
@@ -1,22 +0,0 @@
#!/bin/bash
while getopts ":-:" optchar; do
[[ "${optchar}" == "-" ]] || continue
case "${OPTARG}" in
datadir=* )
PGDATA=${OPTARG#*=}
;;
dbname=* )
DBNAME=${OPTARG#*=}
;;
walmethod=* )
WALMETHOD=${OPTARG#*=}
;;
esac
done
[[ -z $PGDATA || -z $DBNAME || -z $WALMETHOD ]] && exit 1
[[ $WALMETHOD != "none" ]] && WALMETHOD="-X $WALMETHOD" || WALMETHOD=""
exec pg_basebackup -D $PGDATA $WALMETHOD -c fast -d $DBNAME
+11
View File
@@ -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)
-21
View File
@@ -1,21 +0,0 @@
#!/bin/bash
set -x
while getopts ":-:" optchar; do
[[ "${optchar}" == "-" ]] || continue
case "${OPTARG}" in
datadir=* )
PGDATA=${OPTARG#*=}
;;
sourcedir=* )
SOURCE=${OPTARG#*=}
;;
esac
done
[[ -z $PGDATA || -z $SOURCE ]] && exit 1
mkdir -p $(dirname $PGDATA)
exec cp -af $SOURCE $PGDATA
+17
View File
@@ -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()), ""))
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
[[ "$3" == "master" ]] || exit
PGPASSWORD=zalando psql -h localhost -U postgres -p $1 -w -tAc "SELECT slot_name FROM pg_replication_slots WHERE slot_type = 'logical'" >> data/postgres0/label
+5
View File
@@ -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")
+17 -12
View File
@@ -171,7 +171,8 @@ class PatroniController(AbstractController):
config['name'] = name config['name'] = name
config['postgresql']['data_dir'] = self._data_dir config['postgresql']['data_dir'] = self._data_dir
config['postgresql']['use_unix_socket'] = True 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({ config['postgresql']['parameters'].update({
'logging_collector': 'on', 'log_destination': 'csvlog', 'log_directory': self._output_dir, 'logging_collector': 'on', 'log_destination': 'csvlog', 'log_directory': self._output_dir,
'log_filename': name + '.log', 'log_statement': 'all', 'log_min_messages': 'debug1', 'log_filename': name + '.log', 'log_statement': 'all', 'log_min_messages': 'debug1',
@@ -258,10 +259,10 @@ class PatroniController(AbstractController):
def backup_source(self): def backup_source(self):
return 'postgres://{username}:{password}@{host}:{port}/{database}'.format(**self._replication) return 'postgres://{username}:{password}@{host}:{port}/{database}'.format(**self._replication)
def backup(self, dest='data/basebackup'): def backup(self, dest=os.path.join('data', 'basebackup')):
subprocess.call([PatroniPoolController.BACKUP_SCRIPT, '--walmethod=none', subprocess.call(PatroniPoolController.BACKUP_SCRIPT + ['--walmethod=none',
'--datadir=' + os.path.join(self._work_directory, dest), '--datadir=' + os.path.join(self._work_directory, dest),
'--dbname=' + self.backup_source]) '--dbname=' + self.backup_source])
class ProcessHang(object): class ProcessHang(object):
@@ -532,7 +533,8 @@ class ExhibitorController(ZooKeeperController):
class PatroniPoolController(object): class PatroniPoolController(object):
BACKUP_SCRIPT = 'features/backup_create.sh' 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): def __init__(self, context):
self._context = context self._context = context
@@ -593,7 +595,7 @@ class PatroniPoolController(object):
'bootstrap': { 'bootstrap': {
'method': 'pg_basebackup', 'method': 'pg_basebackup',
'pg_basebackup': { 'pg_basebackup': {
'command': self.BACKUP_SCRIPT + ' --walmethod=stream --dbname=' + f.backup_source 'command': " ".join(self.BACKUP_SCRIPT) + ' --walmethod=stream --dbname=' + f.backup_source
}, },
'dcs': { 'dcs': {
'postgresql': { 'postgresql': {
@@ -606,8 +608,9 @@ class PatroniPoolController(object):
'postgresql': { 'postgresql': {
'parameters': { 'parameters': {
'archive_mode': 'on', 'archive_mode': 'on',
'archive_command': 'mkdir -p {0} && test ! -f {0}/%f && cp %p {0}/%f'.format( 'archive_command': (self.ARCHIVE_RESTORE_SCRIPT + ' --mode archive ' +
os.path.join(self.patroni_path, 'data', 'wal_archive')) '--dirname {} --filename %f --pathname %p').format(
os.path.join(self.patroni_path, 'data', 'wal_archive'))
}, },
'authentication': { 'authentication': {
'superuser': {'password': 'zalando1'}, 'superuser': {'password': 'zalando1'},
@@ -623,12 +626,14 @@ class PatroniPoolController(object):
'bootstrap': { 'bootstrap': {
'method': 'backup_restore', 'method': 'backup_restore',
'backup_restore': { 'backup_restore': {
'command': 'features/backup_restore.sh --sourcedir=' + os.path.join(self.patroni_path, 'command': (sys.executable + ' features/backup_restore.py --sourcedir=' +
'data', 'basebackup'), os.path.join(self.patroni_path, 'data', 'basebackup')),
'recovery_conf': { 'recovery_conf': {
'recovery_target_action': 'promote', 'recovery_target_action': 'promote',
'recovery_target_timeline': 'latest', 'recovery_target_timeline': 'latest',
'restore_command': 'cp {0}/data/wal_archive/%f %p'.format(self.patroni_path) 'restore_command': (self.ARCHIVE_RESTORE_SCRIPT + ' --mode restore ' +
'--dirname {} --filename %f --pathname %p').format(
os.path.join(self.patroni_path, 'data', 'wal_archive'))
} }
} }
}, },
+1 -1
View File
@@ -30,7 +30,7 @@ Feature: standby cluster
When I issue a GET request to http://127.0.0.1:8009/standby_leader When I issue a GET request to http://127.0.0.1:8009/standby_leader
Then I receive a response code 200 Then I receive a response code 200
And I receive a response role standby_leader And I receive a response role standby_leader
And there is a postgres1_cb.log with "on_start replica batman1\non_role_change standby_leader batman1" in postgres1 data directory 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 When I start postgres2 in a cluster batman1
Then postgres2 role is the replica after 24 seconds Then postgres2 role is the replica after 24 seconds
And table foo is present on postgres2 after 20 seconds And table foo is present on postgres2 after 20 seconds
+1 -1
View File
@@ -13,7 +13,7 @@ def start_patroni_with_a_name_value_tag(context, name, tag_name, tag_value):
def check_label(context, label, content, name): def check_label(context, label, content, name):
label = context.pctl.read_label(name, label) label = context.pctl.read_label(name, label)
label = label.replace('\n', '\\n') label = label.replace('\n', '\\n')
assert label == content, "{0} is not equal to {1}".format(label, content) assert content in label, "{0} doesn't contain {1}".format(label, content)
@step('I create label with "{content:w}" in {name:w} data directory') @step('I create label with "{content:w}" in {name:w} data directory')
+5 -4
View File
@@ -1,4 +1,5 @@
import os import os
import sys
import time import time
from behave import step from behave import step
@@ -9,7 +10,7 @@ SELECT * FROM pg_catalog.pg_stat_replication
WHERE application_name = '{0}' WHERE application_name = '{0}'
""" """
callback = "bash -c 'echo \"${*: -3:1} ${*: -2:1} ${*: -1:1}\" >> data/$1/$1_cb.log' -- " callback = sys.executable + " features/callback2.py "
@step('I start {name:w} with callback configured') @step('I start {name:w} with callback configured')
@@ -17,7 +18,7 @@ def start_patroni_with_callbacks(context, name):
return context.pctl.start(name, custom_config={ return context.pctl.start(name, custom_config={
"postgresql": { "postgresql": {
"callbacks": { "callbacks": {
"on_role_change": "features/callback.sh" "on_role_change": sys.executable + " features/callback.py"
} }
} }
}) })
@@ -30,8 +31,8 @@ def start_patroni(context, name, cluster_name):
"postgresql": { "postgresql": {
"callbacks": {c: callback + name for c in ('on_start', 'on_stop', 'on_restart', 'on_role_change')}, "callbacks": {c: callback + name for c in ('on_start', 'on_stop', 'on_restart', 'on_role_change')},
"backup_restore": { "backup_restore": {
"command": "features/backup_restore.sh --sourcedir=" + os.path.join(context.pctl.patroni_path, "command": (sys.executable + " features/backup_restore.py --sourcedir=" +
'data', 'basebackup')} os.path.join(context.pctl.patroni_path, 'data', 'basebackup'))}
} }
}) })
@@ -106,6 +106,20 @@ objects:
application: ${APPLICATION_NAME} application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME} cluster-name: ${PATRONI_CLUSTER_NAME}
spec: 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: containers:
- env: - env:
- name: PATRONI_KUBERNETES_POD_IP - name: PATRONI_KUBERNETES_POD_IP
+16 -2
View File
@@ -9,6 +9,7 @@ from patroni.version import __version__
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
PATRONI_ENV_PREFIX = 'PATRONI_' PATRONI_ENV_PREFIX = 'PATRONI_'
KUBERNETES_ENV_PREFIX = 'KUBERNETES_'
class Patroni(object): class Patroni(object):
@@ -159,22 +160,35 @@ class Patroni(object):
self.api.shutdown() self.api.shutdown()
except Exception: except Exception:
logger.exception('Exception during RestApi.shutdown') logger.exception('Exception during RestApi.shutdown')
self.ha.shutdown() try:
self.ha.shutdown()
except Exception:
logger.exception('Exception during Ha.shutdown')
self.logger.shutdown() self.logger.shutdown()
def patroni_main(): def patroni_main():
import argparse import argparse
from multiprocessing import freeze_support
from patroni.config import Config, ConfigParseError from patroni.config import Config, ConfigParseError
from patroni.validator import schema
freeze_support()
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(__version__)) 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='', parser.add_argument('configfile', nargs='?', default='',
help='Patroni may also read the configuration from the {0} environment variable' help='Patroni may also read the configuration from the {0} environment variable'
.format(Config.PATRONI_CONFIG_VARIABLE)) .format(Config.PATRONI_CONFIG_VARIABLE))
args = parser.parse_args() args = parser.parse_args()
try: try:
conf = Config(args.configfile) if args.validate_config:
conf = Config(args.configfile, validator=schema)
sys.exit()
else:
conf = Config(args.configfile)
except ConfigParseError as e: except ConfigParseError as e:
if e.value: if e.value:
print(e.value) print(e.value)
+1
View File
@@ -59,6 +59,7 @@ class Config(object):
'maximum_lag_on_failover': 1048576, 'maximum_lag_on_failover': 1048576,
'check_timeline': False, 'check_timeline': False,
'master_start_timeout': 300, 'master_start_timeout': 300,
'master_stop_timeout': 0,
'synchronous_mode': False, 'synchronous_mode': False,
'synchronous_mode_strict': False, 'synchronous_mode_strict': False,
'standby_cluster': { 'standby_cluster': {
+102 -54
View File
@@ -6,6 +6,7 @@ import click
import codecs import codecs
import datetime import datetime
import dateutil.parser import dateutil.parser
import dateutil.tz
import cdiff import cdiff
import copy import copy
import difflib import difflib
@@ -19,7 +20,6 @@ import subprocess
import sys import sys
import tempfile import tempfile
import time import time
import tzlocal
import yaml import yaml
from click import ClickException from click import ClickException
@@ -31,7 +31,7 @@ from patroni.postgresql.misc import postgres_version_to_int
from patroni.utils import cluster_as_json, patch_config, polling_loop from patroni.utils import cluster_as_json, patch_config, polling_loop
from patroni.request import PatroniRequest from patroni.request import PatroniRequest
from patroni.version import __version__ from patroni.version import __version__
from prettytable import PrettyTable from prettytable import ALL, FRAME, PrettyTable
from six.moves.urllib_parse import urlparse from six.moves.urllib_parse import urlparse
CONFIG_DIR_PATH = click.get_app_dir('patroni') CONFIG_DIR_PATH = click.get_app_dir('patroni')
@@ -46,14 +46,42 @@ class PatroniCtlException(ClickException):
pass pass
class PatronictlPrettyTable(PrettyTable):
def __init__(self, header, *args, **kwargs):
PrettyTable.__init__(self, *args, **kwargs)
self.__table_header = header
self.__hline_num = 0
self.__hline = None
def _is_first_hline(self):
return self.__hline_num == 0
def _set_hline(self, value):
self.__hline = value
def _get_hline(self):
ret = self.__hline
# Inject nice table header
if self._is_first_hline() and self.__table_header:
header = self.__table_header[:len(ret) - 2]
ret = "".join([ret[0], header, ret[1 + len(header):]])
self.__hline_num += 1
return ret
_hrule = property(_get_hline, _set_hline)
def parse_dcs(dcs): def parse_dcs(dcs):
if dcs is None: if dcs is None:
return None return None
elif '//' not in dcs:
dcs = '//' + dcs
parsed = urlparse(dcs) parsed = urlparse(dcs)
scheme = parsed.scheme scheme = parsed.scheme
if scheme == '' and parsed.netloc == '':
parsed = urlparse('//' + dcs)
port = int(parsed.port) if parsed.port else None port = int(parsed.port) if parsed.port else None
if scheme == '': if scheme == '':
@@ -69,7 +97,11 @@ def load_config(path, dcs):
from patroni.config import Config from patroni.config import Config
if not (os.path.exists(path) and os.access(path, os.R_OK)): if not (os.path.exists(path) and os.access(path, os.R_OK)):
logging.debug('Ignoring configuration file "%s". It does not exists or is not readable.', path) if path != CONFIG_FILE_PATH: # bail if non-default config location specified but file not found / readable
raise PatroniCtlException('Provided config file {0} not existing or no read rights.'
' Check the -c/--config-file parameter'.format(path))
else:
logging.debug('Ignoring configuration file "%s". It does not exists or is not readable.', path)
else: else:
logging.debug('Loading configuration from file %s', path) logging.debug('Loading configuration from file %s', path)
config = Config(path, validator=None).copy() config = Config(path, validator=None).copy()
@@ -90,7 +122,7 @@ def store_config(config, path):
yaml.dump(config, fd) yaml.dump(config, fd)
option_format = click.option('--format', '-f', 'fmt', help='Output format (pretty, json, yaml)', default='pretty') option_format = click.option('--format', '-f', 'fmt', help='Output format (pretty, tsv, json, yaml)', default='pretty')
option_watchrefresh = click.option('-w', '--watch', type=float, help='Auto update the screen every X seconds') option_watchrefresh = click.option('-w', '--watch', type=float, help='Auto update the screen every X seconds')
option_watch = click.option('-W', is_flag=True, help='Auto update the screen every 2 seconds') option_watch = click.option('-W', is_flag=True, help='Auto update the screen every 2 seconds')
option_force = click.option('--force', is_flag=True, help='Do not ask for confirmation at any point') option_force = click.option('--force', is_flag=True, help='Do not ask for confirmation at any point')
@@ -133,31 +165,33 @@ def request_patroni(member, method='GET', endpoint=None, data=None):
return request_executor(member, method, endpoint, data) return request_executor(member, method, endpoint, data)
def print_output(columns, rows=None, alignment=None, fmt='pretty', header=True, delimiter='\t'): def print_output(columns, rows, alignment=None, fmt='pretty', header=None, delimiter='\t'):
rows = rows or [] if fmt in {'json', 'yaml', 'yml'}:
if fmt == 'pretty': elements = [{k: v for k, v in zip(columns, r) if not header or str(v)} for r in rows]
t = PrettyTable(columns) func = json.dumps if fmt == 'json' else format_config_for_editing
for k, v in (alignment or {}).items(): click.echo(func(elements))
t.align[k] = v elif fmt in {'pretty', 'tsv'}:
for r in rows: list_cluster = bool(header and columns and columns[0] == 'Cluster')
t.add_row(r) if list_cluster and 'Tags' in columns: # we want to format member tags as YAML
click.echo(t) i = columns.index('Tags')
return for row in rows:
if row[i]:
row[i] = format_config_for_editing(row[i], fmt == 'tsv').strip()
if list_cluster and fmt == 'pretty': # skip cluster name if pretty-printing
columns = columns[1:] if columns else []
rows = [row[1:] for row in rows]
if fmt in ['json', 'yaml', 'yml']: if fmt == 'tsv':
elements = [dict(zip(columns, r)) for r in rows] for r in ([columns] if columns else []) + rows:
if fmt == 'json': click.echo(delimiter.join(map(str, r)))
click.echo(json.dumps(elements)) else:
elif fmt in ('yaml', 'yml'): hrules = ALL if any(any(isinstance(c, six.string_types) and '\n' in c for c in r) for r in rows) else FRAME
click.echo(yaml.safe_dump(elements, encoding=None, default_flow_style=False, allow_unicode=True, width=200)) table = PatronictlPrettyTable(header, columns, hrules=hrules)
for k, v in (alignment or {}).items():
if fmt == 'tsv': table.align[k] = v
if columns is not None and header: for r in rows:
click.echo(delimiter.join(columns)) table.add_row(r)
click.echo(table)
for r in rows:
c = [str(c) for c in r]
click.echo(delimiter.join(c))
def watching(w, watch, max_count=None, clear=True): def watching(w, watch, max_count=None, clear=True):
@@ -306,8 +340,7 @@ def dsn(obj, cluster_name, role, member):
@ctl.command('query', help='Query a Patroni PostgreSQL member') @ctl.command('query', help='Query a Patroni PostgreSQL member')
@arg_cluster_name @arg_cluster_name
@option_format @click.option('--format', 'fmt', help='Output format (pretty, tsv, json, yaml)', default='tsv')
@click.option('--format', 'fmt', help='Output format (pretty, json)', default='tsv')
@click.option('--file', '-f', 'p_file', help='Execute the SQL commands from this file', type=click.File('rb')) @click.option('--file', '-f', 'p_file', help='Execute the SQL commands from this file', type=click.File('rb'))
@click.option('--password', help='force password prompt', is_flag=True) @click.option('--password', help='force password prompt', is_flag=True)
@click.option('-U', '--username', help='database user name', type=str) @click.option('-U', '--username', help='database user name', type=str)
@@ -364,8 +397,8 @@ def query(
if cursor is None: if cursor is None:
cluster = dcs.get_cluster() cluster = dcs.get_cluster()
output, cursor = query_member(cluster, cursor, member, role, command, connect_parameters) output, header = query_member(cluster, cursor, member, role, command, connect_parameters)
print_output(None, output, fmt=fmt, delimiter=delimiter) print_output(header, output, fmt=fmt, delimiter=delimiter)
def query_member(cluster, cursor, member, role, command, connect_parameters): def query_member(cluster, cursor, member, role, command, connect_parameters):
@@ -382,15 +415,8 @@ def query_member(cluster, cursor, member, role, command, connect_parameters):
logging.debug(message) logging.debug(message)
return [[timestamp(0), message]], None return [[timestamp(0), message]], None
cursor.execute('SELECT pg_catalog.pg_is_in_recovery()')
in_recovery = cursor.fetchone()[0]
if in_recovery and role == 'master' or not in_recovery and role == 'replica':
cursor.connection.close()
return None, None
cursor.execute(command) cursor.execute(command)
return cursor.fetchall(), cursor return cursor.fetchall(), [d.name for d in cursor.description]
except (psycopg2.OperationalError, psycopg2.DatabaseError) as oe: except (psycopg2.OperationalError, psycopg2.DatabaseError) as oe:
logging.debug(oe) logging.debug(oe)
if cursor is not None and not cursor.connection.closed: if cursor is not None and not cursor.connection.closed:
@@ -445,7 +471,7 @@ def parse_scheduled(scheduled):
try: try:
scheduled_at = dateutil.parser.parse(scheduled) scheduled_at = dateutil.parser.parse(scheduled)
if scheduled_at.tzinfo is None: if scheduled_at.tzinfo is None:
scheduled_at = tzlocal.get_localzone().localize(scheduled_at) scheduled_at = scheduled_at.replace(tzinfo=dateutil.tz.tzlocal())
except (ValueError, TypeError): except (ValueError, TypeError):
message = 'Unable to parse scheduled timestamp ({0}). It should be in an unambiguous format (e.g. ISO 8601)' message = 'Unable to parse scheduled timestamp ({0}). It should be in an unambiguous format (e.g. ISO 8601)'
raise PatroniCtlException(message.format(scheduled)) raise PatroniCtlException(message.format(scheduled))
@@ -558,20 +584,39 @@ def restart(obj, cluster_name, member_names, force, role, p_any, scheduled, vers
@click.argument('cluster_name') @click.argument('cluster_name')
@click.argument('member_names', nargs=-1) @click.argument('member_names', nargs=-1)
@option_force @option_force
@click.option('--wait', help='Wait until reinitialization completes', is_flag=True)
@click.pass_obj @click.pass_obj
def reinit(obj, cluster_name, member_names, force): def reinit(obj, cluster_name, member_names, force, wait):
cluster = get_dcs(obj, cluster_name).get_cluster() cluster = get_dcs(obj, cluster_name).get_cluster()
members = get_members(cluster, cluster_name, member_names, None, force, 'reinitialize') members = get_members(cluster, cluster_name, member_names, None, force, 'reinitialize')
wait_on_members = []
for member in members: for member in members:
body = {'force': force} body = {'force': force}
while True: while True:
r = request_patroni(member, 'post', 'reinitialize', body) r = request_patroni(member, 'post', 'reinitialize', body)
if not check_response(r, member.name, 'reinitialize') and r.data.endswith(b' already in progress') \ started = check_response(r, member.name, 'reinitialize')
if not started and r.data.endswith(b' already in progress') \
and not force and click.confirm('Do you want to cancel it and reinitialize anyway?'): and not force and click.confirm('Do you want to cancel it and reinitialize anyway?'):
body['force'] = True body['force'] = True
continue continue
break break
if started and wait:
wait_on_members.append(member)
last_display = []
while wait_on_members:
if wait_on_members != last_display:
click.echo('Waiting for reinitialize to complete on: {0}'.format(
", ".join(member.name for member in wait_on_members))
)
last_display[:] = wait_on_members
time.sleep(2)
for member in wait_on_members:
data = json.loads(request_patroni(member, 'get', 'patroni').data.decode('utf-8'))
if data.get('state') != 'creating replica':
click.echo('Reinitialize is completed on: {0}'.format(member.name))
wait_on_members.remove(member)
def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, force, scheduled=None): def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, force, scheduled=None):
@@ -704,27 +749,29 @@ def switchover(obj, cluster_name, master, candidate, force, scheduled):
def output_members(cluster, name, extended=False, fmt='pretty'): def output_members(cluster, name, extended=False, fmt='pretty'):
rows = [] rows = []
logging.debug(cluster) logging.debug(cluster)
initialize = {None: 'uninitialized', '': 'initializing'}.get(cluster.initialize, cluster.initialize)
cluster = cluster_as_json(cluster) cluster = cluster_as_json(cluster)
columns = ['Cluster', 'Member', 'Host', 'Role', 'State', 'TL', 'Lag in MB'] columns = ['Cluster', 'Member', 'Host', 'Role', 'State', 'TL', 'Lag in MB']
for c in ('Pending restart', 'Scheduled restart'): for c in ('Pending restart', 'Scheduled restart', 'Tags'):
if extended or any(m.get(c.lower().replace(' ', '_')) for m in cluster['members']): if extended or any(m.get(c.lower().replace(' ', '_')) for m in cluster['members']):
columns.append(c) columns.append(c)
# Show Host as 'host:port' if somebody is running on non-standard port or two nodes are running on the same host # Show Host as 'host:port' if somebody is running on non-standard port or two nodes are running on the same host
append_port = any(m['port'] != 5432 for m in cluster['members']) or\ members = [m for m in cluster['members'] if 'host' in m]
len(set(m['host'] for m in cluster['members'])) < len(cluster['members']) append_port = any('port' in m and m['port'] != 5432 for m in members) or\
len(set(m['host'] for m in cluster['members'])) < len(members)
for m in cluster['members']: for m in cluster['members']:
logging.debug(m) logging.debug(m)
lag = m.get('lag', '') lag = m.get('lag', '')
m.update(cluster=name, member=m['name'], tl=m.get('timeline', ''), m.update(cluster=name, member=m['name'], host=m.get('host'), tl=m.get('timeline', ''),
role='' if m['role'] == 'replica' else m['role'].replace('_', ' ').title(), role='' if m['role'] == 'replica' else m['role'].replace('_', ' ').title(),
lag_in_mb=round(lag/1024/1024) if isinstance(lag, six.integer_types) else lag, lag_in_mb=round(lag/1024/1024) if isinstance(lag, six.integer_types) else lag,
pending_restart='*' if m.get('pending_restart') else '') pending_restart='*' if m.get('pending_restart') else '')
if append_port: if append_port and m['host'] and m.get('port'):
m['host'] = ':'.join([m['host'], str(m['port'])]) m['host'] = ':'.join([m['host'], str(m['port'])])
if 'scheduled_restart' in m: if 'scheduled_restart' in m:
@@ -735,7 +782,8 @@ def output_members(cluster, name, extended=False, fmt='pretty'):
rows.append([m.get(n.lower().replace(' ', '_'), '') for n in columns]) rows.append([m.get(n.lower().replace(' ', '_'), '') for n in columns])
print_output(columns, rows, {'Lag in MB': 'r', 'TL': 'r'}, fmt) print_output(columns, rows, {'Lag in MB': 'r', 'TL': 'r', 'Tags': 'l'},
fmt, ' Cluster: {0} ({1}) '.format(name, initialize))
if fmt != 'pretty': # Omit service info when using machine-readable formats if fmt != 'pretty': # Omit service info when using machine-readable formats
return return
@@ -848,7 +896,7 @@ def scaffold(obj, cluster_name, sysid):
click.echo("Cluster {0} has been created successfully".format(cluster_name)) click.echo("Cluster {0} has been created successfully".format(cluster_name))
@ctl.command('flush', help='Flush scheduled events') @ctl.command('flush', help='Discard scheduled events (restarts only currently)')
@click.argument('cluster_name') @click.argument('cluster_name')
@click.argument('member_names', nargs=-1) @click.argument('member_names', nargs=-1)
@click.argument('target', type=click.Choice(['restart'])) @click.argument('target', type=click.Choice(['restart']))
@@ -981,12 +1029,12 @@ def show_diff(before_editing, after_editing):
click.echo(line.rstrip('\n')) click.echo(line.rstrip('\n'))
def format_config_for_editing(data): def format_config_for_editing(data, default_flow_style=False):
"""Formats configuration as YAML for human consumption. """Formats configuration as YAML for human consumption.
:param data: configuration as nested dictionaries :param data: configuration as nested dictionaries
:returns unicode YAML of the configuration""" :returns unicode YAML of the configuration"""
return yaml.safe_dump(data, default_flow_style=False, encoding=None, allow_unicode=True) return yaml.safe_dump(data, default_flow_style=default_flow_style, encoding=None, allow_unicode=True, width=200)
def apply_config_changes(before_editing, data, kvpairs): def apply_config_changes(before_editing, data, kvpairs):
+40 -27
View File
@@ -66,8 +66,11 @@ def dcs_modules():
module_prefix = __package__ + '.' module_prefix = __package__ + '.'
if getattr(sys, 'frozen', False): if getattr(sys, 'frozen', False):
importer = pkgutil.get_importer(dcs_dirname) toc = set()
return [module for module in list(importer.toc) if module.startswith(module_prefix) and module.count('.') == 2] 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: else:
return [module_prefix + name for _, name, is_pkg in pkgutil.iter_modules([dcs_dirname]) if not is_pkg] return [module_prefix + name for _, name, is_pkg in pkgutil.iter_modules([dcs_dirname]) if not is_pkg]
@@ -137,10 +140,10 @@ class Member(namedtuple('Member', 'index,name,session,data')):
@property @property
def conn_url(self): def conn_url(self):
conn_url = self.data.get('conn_url') conn_url = self.data.get('conn_url')
conn_kwargs = self.data.get('conn_kwargs')
if conn_url: if conn_url:
return conn_url return conn_url
conn_kwargs = self.data.get('conn_kwargs')
if conn_kwargs: if conn_kwargs:
conn_url = uri('postgresql', (conn_kwargs.get('host'), conn_kwargs.get('port', 5432))) conn_url = uri('postgresql', (conn_kwargs.get('host'), conn_kwargs.get('port', 5432)))
self.data['conn_url'] = conn_url self.data['conn_url'] = conn_url
@@ -148,16 +151,19 @@ class Member(namedtuple('Member', 'index,name,session,data')):
def conn_kwargs(self, auth=None): def conn_kwargs(self, auth=None):
defaults = { defaults = {
"host": "", "host": None,
"port": "", "port": None,
"database": "" "database": None
} }
ret = self.data.get('conn_kwargs') ret = self.data.get('conn_kwargs')
if ret: if ret:
defaults.update(ret) defaults.update(ret)
ret = defaults ret = defaults
else: 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 = { ret = {
'host': r.hostname, 'host': r.hostname,
'port': r.port or 5432, 'port': r.port or 5432,
@@ -167,7 +173,7 @@ class Member(namedtuple('Member', 'index,name,session,data')):
# apply any remaining authentication parameters # apply any remaining authentication parameters
if auth and isinstance(auth, dict): if auth and isinstance(auth, dict):
ret.update(auth) ret.update({k: v for k, v in auth.items() if v is not None})
if 'username' in auth: if 'username' in auth:
ret['user'] = ret.pop('username') ret['user'] = ret.pop('username')
return ret return ret
@@ -240,21 +246,25 @@ class Leader(namedtuple('Leader', 'index,session,member')):
def conn_url(self): def conn_url(self):
return self.member.conn_url return self.member.conn_url
@property
def data(self):
return self.member.data
@property @property
def timeline(self): def timeline(self):
return self.member.data.get('timeline') return self.data.get('timeline')
@property @property
def checkpoint_after_promote(self): def checkpoint_after_promote(self):
""" """
>>> Leader(1, '', Member.from_node(1, '', '', '{"version":"z"}')).checkpoint_after_promote >>> Leader(1, '', Member.from_node(1, '', '', '{"version":"z"}')).checkpoint_after_promote
""" """
version = self.member.data.get('version') version = self.data.get('version')
if version: if version:
try: try:
# 1.5.6 is the last version which doesn't expose checkpoint_after_promote: false # 1.5.6 is the last version which doesn't expose checkpoint_after_promote: false
if tuple(map(int, version.split('.'))) > (1, 5, 6): if tuple(map(int, version.split('.'))) > (1, 5, 6):
return self.member.data['role'] == 'master' and 'checkpoint_after_promote' not in self.member.data return self.data['role'] == 'master' and 'checkpoint_after_promote' not in self.data
except Exception: except Exception:
logger.debug('Failed to parse Patroni version %s', version) logger.debug('Failed to parse Patroni version %s', version)
@@ -331,6 +341,10 @@ class ClusterConfig(namedtuple('ClusterConfig', 'index,data,modify_index')):
self.data.get('permanent_slots') or self.data.get('slots') self.data.get('permanent_slots') or self.data.get('slots')
) or {} ) or {}
@property
def max_timelines_history(self):
return self.data.get('max_timelines_history', 0)
class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')): class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')):
"""Immutable object (namedtuple) which represents last observed synhcronous replication state """Immutable object (namedtuple) which represents last observed synhcronous replication state
@@ -445,21 +459,21 @@ class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operat
def is_synchronous_mode(self): def is_synchronous_mode(self):
return self.check_mode('synchronous_mode') return self.check_mode('synchronous_mode')
def get_replication_slots(self, name, role): 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 # 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 current master, because that member would replicate from elsewhere. We still create the slot if
# the replicatefrom destination member is currently not a member of the cluster (fallback to the # the replicatefrom destination member is currently not a member of the cluster (fallback to the
# master), or if replicatefrom destination member happens to be the current master # master), or if replicatefrom destination member happens to be the current master
use_slots = self.config and self.config.data.get('postgresql', {}).get('use_slots', True) use_slots = self.config and self.config.data.get('postgresql', {}).get('use_slots', True)
if role in ('master', 'standby_leader'): if role in ('master', 'standby_leader'):
slot_members = [m.name for m in self.members if use_slots and m.name != name and 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 == name or (m.replicatefrom is None or m.replicatefrom == my_name or
not self.has_member(m.replicatefrom))] not self.has_member(m.replicatefrom))]
permanent_slots = (self.config and self.config.permanent_slots or {}).copy() permanent_slots = (self.config and self.config.permanent_slots or {}).copy()
else: else:
# only manage slots for replicas that replicate from this one, except for the leader among them # 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 slot_members = [m.name for m in self.members if use_slots and
m.replicatefrom == name and m.name != self.leader.name] m.replicatefrom == my_name and m.name != self.leader.name]
permanent_slots = {} permanent_slots = {}
slots = {slot_name_from_member_name(name): {'type': 'physical'} for name in slot_members} slots = {slot_name_from_member_name(name): {'type': 'physical'} for name in slot_members}
@@ -480,22 +494,21 @@ class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operat
logger.error("Slot name may only contain lower case letters, numbers, and the underscore chars") logger.error("Slot name may only contain lower case letters, numbers, and the underscore chars")
continue continue
if name in slots: value = deepcopy(value) if value else {'type': 'physical'}
logger.error("Permanent replication slot {'%s': %s} is conflicting with" +
" physical replication slot for cluster member", name, value)
continue
value = deepcopy(value)
if not value:
value = {'type': 'physical'}
if isinstance(value, dict): if isinstance(value, dict):
if 'type' not in value: if 'type' not in value:
value['type'] = 'logical' if value.get('database') and value.get('plugin') else 'physical' value['type'] = 'logical' if value.get('database') and value.get('plugin') else 'physical'
if value['type'] == 'physical' or value['type'] == 'logical' \ if value['type'] == 'physical':
and value.get('database') and value.get('plugin'): if name != my_name: # Don't try to create permanent physical replication slot for yourself
slots[name] = value 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 continue
logger.error("Bad value for slot '%s' in permanent_slots: %s", name, permanent_slots[name]) logger.error("Bad value for slot '%s' in permanent_slots: %s", name, permanent_slots[name])
+2 -3
View File
@@ -53,8 +53,7 @@ class HTTPClient(object):
kwargs['cert_file'] = cert kwargs['cert_file'] = cert
if ca_cert: if ca_cert:
kwargs['ca_certs'] = ca_cert kwargs['ca_certs'] = ca_cert
if verify or ca_cert: kwargs['cert_reqs'] = ssl.CERT_REQUIRED if verify or ca_cert else ssl.CERT_NONE
kwargs['cert_reqs'] = ssl.CERT_REQUIRED
self.http = urllib3.PoolManager(num_pools=10, **kwargs) self.http = urllib3.PoolManager(num_pools=10, **kwargs)
self._ttl = None self._ttl = None
@@ -217,7 +216,7 @@ class Consul(AbstractDCS):
self.set_retry_timeout(config['retry_timeout']) self.set_retry_timeout(config['retry_timeout'])
self.set_ttl(config.get('ttl') or 30) self.set_ttl(config.get('ttl') or 30)
self._last_session_refresh = 0 self._last_session_refresh = 0
self.__session_checks = config.get('checks') self.__session_checks = config.get('checks', [])
self._register_service = config.get('register_service', False) self._register_service = config.get('register_service', False)
if self._register_service: if self._register_service:
self._service_name = service_name_from_scope_name(self._scope) self._service_name = service_name_from_scope_name(self._scope)
+120 -90
View File
@@ -11,6 +11,7 @@ import time
from dns.exception import DNSException from dns.exception import DNSException
from dns import resolver from dns import resolver
from urllib3 import Timeout
from urllib3.exceptions import HTTPError, ReadTimeoutError, ProtocolError from urllib3.exceptions import HTTPError, ReadTimeoutError, ProtocolError
from six.moves.queue import Queue from six.moves.queue import Queue
from six.moves.http_client import HTTPException from six.moves.http_client import HTTPException
@@ -69,12 +70,15 @@ class DnsCachingResolver(Thread):
def resolve_async(self, host, port, attempt=0): def resolve_async(self, host, port, attempt=0):
self._resolve_queue.put(((host, port), attempt)) self._resolve_queue.put(((host, port), attempt))
def remove(self, host, port):
self._cache.pop((host, port), None)
@staticmethod @staticmethod
def _do_resolve(host, port): def _do_resolve(host, port):
try: try:
return socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP) return socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
except socket.gaierror: except Exception as e:
logger.warning('failed to resolve host %s', host) logger.warning('failed to resolve host %s: %s', host, e)
return [] return []
@@ -91,6 +95,7 @@ class Client(etcd.Client):
# Workaround for the case when https://github.com/jplana/python-etcd/pull/196 is not applied # 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.http.connection_pool_kw.pop('ssl_version', None)
self._config = config self._config = config
self._initial_machines_cache = []
self._load_machines_cache() self._load_machines_cache()
self._allow_reconnect = True self._allow_reconnect = True
# allow passing retry argument to api_execute in params # allow passing retry argument to api_execute in params
@@ -98,14 +103,13 @@ class Client(etcd.Client):
self._read_options.add('retry') self._read_options.add('retry')
self._del_conditions.add('retry') self._del_conditions.add('retry')
def _calculate_timeouts(self, etcd_nodes=None, timeout=None): def _calculate_timeouts(self, etcd_nodes, timeout=None):
"""Calculate a request timeout and number of retries per single etcd node. """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. 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 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. 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.""" No retries for clusters with 3 or more nodes. We better rely on switching to a different node."""
etcd_nodes = etcd_nodes or len(self._machines_cache) + 1
per_node_timeout = timeout = float(timeout or self.read_timeout) per_node_timeout = timeout = float(timeout or self.read_timeout)
max_retries = 4 - min(etcd_nodes, 3) max_retries = 4 - min(etcd_nodes, 3)
@@ -130,19 +134,25 @@ class Client(etcd.Client):
basic_auth = ':'.join((self.username, self.password)) if self.username and self.password else None 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) return urllib3.make_headers(basic_auth=basic_auth, user_agent=USER_AGENT)
def _build_request_parameters(self, timeout=None): def _build_request_parameters(self, etcd_nodes, timeout=None):
kwargs = {'headers': self._get_headers(), 'redirect': self.allow_redirect} kwargs = {'headers': self._get_headers(), 'redirect': self.allow_redirect}
if timeout is not None: if timeout is not None:
kwargs.update(retries=0, timeout=timeout) kwargs.update(retries=0, timeout=timeout)
else: else:
_, per_node_timeout, per_node_retries = self._calculate_timeouts() _, per_node_timeout, per_node_retries = self._calculate_timeouts(etcd_nodes)
kwargs.update(timeout=per_node_timeout, retries=per_node_retries) 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 return kwargs
def set_machines_cache_ttl(self, cache_ttl): def set_machines_cache_ttl(self, cache_ttl):
self._machines_cache_ttl = 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 @property
def machines(self): def machines(self):
"""Original `machines` method(property) of `etcd.Client` class raise exception """Original `machines` method(property) of `etcd.Client` class raise exception
@@ -155,58 +165,58 @@ class Client(etcd.Client):
Also this method implements the same timeout-retry logic as `api_execute`, because 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.""" 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: try:
response = self.http.request(self._MGET, self._base_uri + self.version_prefix + '/machines', **kwargs) response = self.http.request(self._MGET, base_uri + self.version_prefix + '/machines', **kwargs)
data = self._handle_server_response(response).data.decode('utf-8') data = self._handle_server_response(response).data.decode('utf-8')
machines = [m.strip() for m in data.split(',') if m.strip()] machines = [m.strip() for m in data.split(',') if m.strip()]
logger.debug("Retrieved list of machines: %s", machines) logger.debug("Retrieved list of machines: %s", machines)
if not machines: if machines:
raise etcd.EtcdException random.shuffle(machines)
random.shuffle(machines) self._update_dns_cache(self._dns_resolver.resolve_async, machines)
for url in machines: return 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
except Exception as e: except Exception as e:
# We can't get the list of machines, if one server is in the self.http.clear()
# machines cache, try on it logger.error("Failed to get list of machines from %s%s: %r", base_uri, self.version_prefix, e)
logger.error("Failed to get list of machines from %s%s: %r", self._base_uri, self.version_prefix, e)
if self._machines_cache: raise etcd.EtcdConnectionFailed('No more machines in the cluster')
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 []
def set_read_timeout(self, timeout): def set_read_timeout(self, timeout):
self._read_timeout = timeout self._read_timeout = timeout
def _do_http_request(self, request_executor, method, url, fields=None, **kwargs): def _do_http_request(self, retry, machines_cache, request_executor, method, path, fields=None, **kwargs):
try: some_request_failed = False
response = request_executor(method, url, fields=fields, **kwargs) for i, base_uri in enumerate(machines_cache):
response.data.decode('utf-8') if i > 0:
self._check_cluster_id(response) logger.info("Retrying on %s", base_uri)
except (HTTPError, HTTPException, socket.error, socket.timeout) as e: try:
if (isinstance(fields, dict) and fields.get("wait") == "true" and response = request_executor(method, base_uri + path, fields=fields, **kwargs)
isinstance(e, (ReadTimeoutError, ProtocolError))): response.data.decode('utf-8')
logger.debug("Watch timed out.") 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, # 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. # whether the key didn't received an update or there is a network problem.
self._machines_cache.insert(0, self._base_uri) if not retry and i + 1 < len(machines_cache):
self._base_uri = self._next_server() self.set_base_uri(machines_cache[i + 1])
raise etcd.EtcdWatchTimedOut("Watch timed out: {0}".format(e), cause=e) if (isinstance(fields, dict) and fields.get("wait") == "true" and
logger.error("Request to server %s failed: %r", self._base_uri, e) isinstance(e, (ReadTimeoutError, ProtocolError))):
logger.info("Reconnection allowed, looking for another server.") logger.debug("Watch timed out.")
self._base_uri = self._next_server(cause=e) raise etcd.EtcdWatchTimedOut("Watch timed out: {0}".format(e), cause=e)
response = False logger.error("Request to server %s failed: %r", base_uri, e)
return response 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): def api_execute(self, path, method, params=None, timeout=None):
if not path.startswith('/'): if not path.startswith('/'):
@@ -229,44 +239,34 @@ class Client(etcd.Client):
elif not self._use_proxies and time.time() - self._machines_cache_updated > self._machines_cache_ttl: elif not self._use_proxies and time.time() - self._machines_cache_updated > self._machines_cache_ttl:
self._refresh_machines_cache() self._refresh_machines_cache()
kwargs.update(self._build_request_parameters(timeout)) machines_cache = self.machines_cache
etcd_nodes = len(machines_cache)
if retry: kwargs.update(self._build_request_parameters(etcd_nodes, timeout))
machines_cache = [self._base_uri] + self._machines_cache
response = False
while True: while True:
try: try:
some_request_failed = False response = self._do_http_request(retry, machines_cache, request_executor, method, path, **kwargs)
while not response: return self._handle_server_response(response)
response = self._do_http_request(request_executor, method, self._base_uri + path, **kwargs) except etcd.EtcdWatchTimedOut:
raise
if response is False: except etcd.EtcdConnectionFailed as ex:
if not retry: try:
raise etcd.EtcdException('{0} {1} request failed'.format(method, path)) if self._load_machines_cache():
some_request_failed = True machines_cache = self.machines_cache
if some_request_failed: etcd_nodes = len(machines_cache)
self._refresh_machines_cache() except Exception as e:
if response: logger.debug('Failed to update list of etcd nodes: %r', e)
break
except etcd.EtcdConnectionFailed:
if not retry:
raise
sleeptime = retry.sleeptime sleeptime = retry.sleeptime
remaining_time = retry.stoptime - sleeptime - time.time() remaining_time = retry.stoptime - sleeptime - time.time()
nodes, timeout, retries = self._calculate_timeouts(len(machines_cache), remaining_time) nodes, timeout, retries = self._calculate_timeouts(etcd_nodes, remaining_time)
if nodes == 0: if nodes == 0:
self._update_machines_cache = True self._update_machines_cache = True
raise raise ex
retry.sleep_func(sleeptime) retry.sleep_func(sleeptime)
retry.update_delay() retry.update_delay()
# We still have some time left. Partially restore `_machines_cache` and retry request # We still have some time left. Partially reduce `machines_cache` and retry request
kwargs.update(timeout=timeout, retries=retries) kwargs.update(timeout=Timeout(connect=max(1, timeout/2), total=timeout), retries=retries)
self._base_uri = machines_cache[0] machines_cache = machines_cache[:nodes]
self._machines_cache = machines_cache[1:nodes]
return self._handle_server_response(response)
@staticmethod @staticmethod
def get_srv_record(host): def get_srv_record(host):
@@ -327,6 +327,13 @@ class Client(etcd.Client):
machines_cache = self._get_machines_cache_from_dns(self._config['host'], self._config['port']) machines_cache = self._get_machines_cache_from_dns(self._config['host'], self._config['port'])
return machines_cache 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): def _load_machines_cache(self):
"""This method should fill up `_machines_cache` from scratch. """This method should fill up `_machines_cache` from scratch.
It could happen only in two cases: It could happen only in two cases:
@@ -338,25 +345,49 @@ class Client(etcd.Client):
if 'srv' not in self._config and 'host' not in self._config and 'hosts' not in self._config: 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') raise Exception('Neither srv, hosts, host nor url are defined in etcd section of config')
self._machines_cache = self._get_machines_cache_from_config() machines_cache = self._get_machines_cache_from_config()
# Can not bootstrap list of etcd-cluster members, giving up # Can not bootstrap list of etcd-cluster members, giving up
if not self._machines_cache: if not machines_cache:
raise etcd.EtcdException raise etcd.EtcdException
# After filling up initial list of machines_cache we should ask etcd-cluster about actual list # enforce resolving dns name,they might get new ips
self._base_uri = self._next_server() self._update_dns_cache(self._dns_resolver.remove, machines_cache)
self._refresh_machines_cache()
self._update_machines_cache = False
def _refresh_machines_cache(self): # The etcd cluster could change its topology over time and depending on how we resolve the initial
self._machines_cache = self._get_machines_cache_from_config() if self._use_proxies else self.machines # topology (list of hosts in the Patroni config or DNS records, A or SRV) we might get into the situation
if self._base_uri in self._machines_cache: # the the real topology doesn't match anymore with the topology resolved from the configuration file.
self._machines_cache.remove(self._base_uri) # In case if the "initial" topology is the same as before we will not override the `_machines_cache`.
elif self._machines_cache: ret = set(machines_cache) != set(self._initial_machines_cache)
self._base_uri = self._next_server() 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() 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): class Etcd(AbstractDCS):
@@ -633,7 +664,6 @@ class Etcd(AbstractDCS):
# than reestablishing http connection every time from every replica. # than reestablishing http connection every time from every replica.
return True return True
except etcd.EtcdWatchTimedOut: except etcd.EtcdWatchTimedOut:
self._client.http.clear()
self._has_failed = False self._has_failed = False
return False return False
except (etcd.EtcdEventIndexCleared, etcd.EtcdWatcherCleared): # Watch failed except (etcd.EtcdEventIndexCleared, etcd.EtcdWatcherCleared): # Watch failed
+34 -7
View File
@@ -31,6 +31,13 @@ class KubernetesRetriableException(k8s_client.rest.ApiException):
self.body = orig.body self.body = orig.body
self.headers = orig.headers self.headers = orig.headers
@property
def sleeptime(self):
try:
return int(self.headers['retry-after'])
except Exception:
return None
class CoreV1ApiProxy(object): class CoreV1ApiProxy(object):
@@ -41,8 +48,22 @@ class CoreV1ApiProxy(object):
self._request_timeout = None self._request_timeout = None
self._use_endpoints = use_endpoints self._use_endpoints = use_endpoints
def set_timeout(self, timeout): def configure_timeouts(self, loop_wait, retry_timeout, ttl):
self._request_timeout = (1, timeout / 3.0) # 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): def __getattr__(self, func):
if func.endswith('_kind'): if func.endswith('_kind'):
@@ -54,7 +75,7 @@ class CoreV1ApiProxy(object):
try: try:
return getattr(self._api, func)(*args, **kwargs) return getattr(self._api, func)(*args, **kwargs)
except k8s_client.rest.ApiException as e: except k8s_client.rest.ApiException as e:
if e.status in (502, 503, 504): # XXX if e.status in (502, 503, 504) or e.headers and 'retry-after' in e.headers: # XXX
raise KubernetesRetriableException(e) raise KubernetesRetriableException(e)
raise raise
return wrapper return wrapper
@@ -92,7 +113,11 @@ class ObjectCache(Thread):
self.start() self.start()
def _list(self): def _list(self):
return self._func(_request_timeout=(self._retry.deadline, Timeout.DEFAULT_TIMEOUT)) try:
return self._func(_request_timeout=(self._retry.deadline, Timeout.DEFAULT_TIMEOUT))
except Exception:
time.sleep(1)
raise
def _watch(self, resource_version): def _watch(self, resource_version):
return self._func(_request_timeout=(self._retry.deadline, Timeout.DEFAULT_TIMEOUT), return self._func(_request_timeout=(self._retry.deadline, Timeout.DEFAULT_TIMEOUT),
@@ -210,8 +235,7 @@ class Kubernetes(AbstractDCS):
self.__subsets = [k8s_client.V1EndpointSubset(addresses=addresses, ports=ports)] self.__subsets = [k8s_client.V1EndpointSubset(addresses=addresses, ports=ports)]
self._should_create_config_service = True self._should_create_config_service = True
self._api = CoreV1ApiProxy(use_endpoints) self._api = CoreV1ApiProxy(use_endpoints)
self.set_retry_timeout(config['retry_timeout']) self.reload_config(config)
self.set_ttl(config.get('ttl') or 30)
self._leader_observed_record = {} self._leader_observed_record = {}
self._leader_observed_time = None self._leader_observed_time = None
self._leader_resource_version = None self._leader_resource_version = None
@@ -250,7 +274,10 @@ class Kubernetes(AbstractDCS):
def set_retry_timeout(self, retry_timeout): def set_retry_timeout(self, retry_timeout):
self._retry.deadline = retry_timeout self._retry.deadline = retry_timeout
self._api.set_timeout(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 @staticmethod
def member(pod): def member(pod):
+2 -2
View File
@@ -76,7 +76,7 @@ class ZooKeeper(AbstractDCS):
self._client.start() 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 """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 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 connection dead and try to connect to another node. Without this "magic" it was taking
@@ -88,7 +88,7 @@ class ZooKeeper(AbstractDCS):
than loop_wait, because we can spend up to 2 seconds when calling `touch_member()` and than loop_wait, because we can spend up to 2 seconds when calling `touch_member()` and
`write_leader_optime()` methods, which also may hang...""" `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] return max(self.loop_wait - 2, 2)*1000, ret[1]
def session_listener(self, state): def session_listener(self, state):
+50 -15
View File
@@ -14,7 +14,7 @@ from patroni.exceptions import DCSError, PostgresConnectionException, PatroniExc
from patroni.postgresql import ACTION_ON_START, ACTION_ON_ROLE_CHANGE from patroni.postgresql import ACTION_ON_START, ACTION_ON_ROLE_CHANGE
from patroni.postgresql.misc import postgres_version_to_int from patroni.postgresql.misc import postgres_version_to_int
from patroni.postgresql.rewind import Rewind from patroni.postgresql.rewind import Rewind
from patroni.utils import polling_loop, tzutc, is_standby_cluster as _is_standby_cluster from patroni.utils import polling_loop, tzutc, is_standby_cluster as _is_standby_cluster, parse_int
from patroni.dcs import RemoteMember from patroni.dcs import RemoteMember
from threading import RLock from threading import RLock
@@ -94,6 +94,11 @@ class Ha(object):
else: else:
return self.patroni.config.check_mode(mode) return self.patroni.config.check_mode(mode)
def master_stop_timeout(self):
""" Master stop timeout """
ret = parse_int(self.patroni.config['master_stop_timeout'])
return ret if ret and ret > 0 and self.is_synchronous_mode() else None
def is_paused(self): def is_paused(self):
return self.check_mode('pause') return self.check_mode('pause')
@@ -191,10 +196,20 @@ class Ha(object):
if self._async_executor.scheduled_action in (None, 'promote') \ if self._async_executor.scheduled_action in (None, 'promote') \
and data['state'] in ['running', 'restarting', 'starting']: and data['state'] in ['running', 'restarting', 'starting']:
try: try:
timeline, wal_position = self.state_handler.timeline_wal_position() timeline, wal_position, pg_control_timeline = self.state_handler.timeline_wal_position()
data['xlog_location'] = wal_position data['xlog_location'] = wal_position
if not timeline: if not timeline:
timeline = self.state_handler.replica_cached_timeline(self._leader_timeline) # So far the only way to get the current timeline on the standby is from
# the replication connection. In order to avoid opening the replication
# connection on every iteration of HA loop we will do it only when noticed
# that the timeline on the primary has changed.
# Unfortunately such optimization isn't possible on the standby_leader,
# therefore we will get the timeline from pg_control, either by calling
# pg_control_checkpoint() on 9.6+ or by parsing the output of pg_controldata.
if self.state_handler.role == 'standby_leader':
timeline = pg_control_timeline or self.state_handler.pg_control_timeline()
else:
timeline = self.state_handler.replica_cached_timeline(self._leader_timeline)
if timeline: if timeline:
data['timeline'] = timeline data['timeline'] = timeline
except Exception: except Exception:
@@ -342,14 +357,26 @@ class Ha(object):
def _get_node_to_follow(self, cluster): def _get_node_to_follow(self, cluster):
# determine the node to follow. If replicatefrom tag is set, # determine the node to follow. If replicatefrom tag is set,
# try to follow the node mentioned there, otherwise, follow the leader. # try to follow the node mentioned there, otherwise, follow the leader.
if self.is_standby_cluster() and (self.cluster.is_unlocked() or self.has_lock(False)): standby_config = self.get_standby_cluster_config()
is_standby_cluster = _is_standby_cluster(standby_config)
if is_standby_cluster and (self.cluster.is_unlocked() or self.has_lock(False)):
node_to_follow = self.get_remote_master() node_to_follow = self.get_remote_master()
elif self.patroni.replicatefrom and self.patroni.replicatefrom != self.state_handler.name: elif self.patroni.replicatefrom and self.patroni.replicatefrom != self.state_handler.name:
node_to_follow = cluster.get_member(self.patroni.replicatefrom) node_to_follow = cluster.get_member(self.patroni.replicatefrom)
else: else:
node_to_follow = cluster.leader node_to_follow = cluster.leader
return node_to_follow if node_to_follow and node_to_follow.name != self.state_handler.name else None node_to_follow = node_to_follow if node_to_follow and node_to_follow.name != self.state_handler.name else None
if node_to_follow and not isinstance(node_to_follow, RemoteMember):
# we are going to abuse Member.data to pass following parameters
params = ('restore_command', 'archive_cleanup_command')
for param in params: # It is highly unlikely to happen, but we want to protect from the case
node_to_follow.data.pop(param, None) # when above-mentioned params came from outside.
if is_standby_cluster:
node_to_follow.data.update({p: standby_config[p] for p in params if standby_config.get(p)})
return node_to_follow
def follow(self, demote_reason, follow_reason, refresh=True): def follow(self, demote_reason, follow_reason, refresh=True):
if refresh: if refresh:
@@ -499,6 +526,7 @@ class Ha(object):
cluster_history = {l[0]: l for l in cluster_history or []} cluster_history = {l[0]: l for l in cluster_history or []}
history = self.state_handler.get_history(master_timeline) history = self.state_handler.get_history(master_timeline)
if history: if history:
history = history[-self.cluster.config.max_timelines_history:]
for line in history: for line in history:
# enrich current history with promotion timestamps stored in DCS # enrich current history with promotion timestamps stored in DCS
if len(line) == 3 and line[0] in cluster_history \ if len(line) == 3 and line[0] in cluster_history \
@@ -585,7 +613,7 @@ class Ha(object):
"""This method tries to determine whether I am healthy enough to became a new leader candidate or not.""" """This method tries to determine whether I am healthy enough to became a new leader candidate or not."""
# We don't call `last_operation()` here because it returns a string # We don't call `last_operation()` here because it returns a string
_, my_wal_position = self.state_handler.timeline_wal_position() _, my_wal_position, _ = self.state_handler.timeline_wal_position()
if check_replication_lag and self.is_lagging(my_wal_position): if check_replication_lag and self.is_lagging(my_wal_position):
logger.info('My wal position exceeds maximum replication lag') logger.info('My wal position exceeds maximum replication lag')
return False # Too far behind last reported wal position on master return False # Too far behind last reported wal position on master
@@ -750,7 +778,8 @@ class Ha(object):
self._rewind.trigger_check_diverged_lsn() self._rewind.trigger_check_diverged_lsn()
self.state_handler.stop(mode_control['stop'], checkpoint=mode_control['checkpoint'], self.state_handler.stop(mode_control['stop'], checkpoint=mode_control['checkpoint'],
on_safepoint=self.watchdog.disable if self.watchdog.is_running else None) on_safepoint=self.watchdog.disable if self.watchdog.is_running else None,
stop_timeout=self.master_stop_timeout())
self.state_handler.set_role('demoted') self.state_handler.set_role('demoted')
self.set_is_leader(False) self.set_is_leader(False)
@@ -916,7 +945,7 @@ class Ha(object):
return msg return msg
# check if the node is ready to be used by pg_rewind # check if the node is ready to be used by pg_rewind
self._rewind.check_for_checkpoint_after_promote() self._rewind.ensure_checkpoint_after_promote()
if self.is_standby_cluster(): if self.is_standby_cluster():
# in case of standby cluster we don't really need to # in case of standby cluster we don't really need to
@@ -1061,7 +1090,7 @@ class Ha(object):
return (False, 'restart failed') return (False, 'restart failed')
def _do_reinitialize(self, cluster): def _do_reinitialize(self, cluster):
self.state_handler.stop('immediate') self.state_handler.stop('immediate', stop_timeout=self.patroni.config['retry_timeout'])
# Commented redundant data directory cleanup here # Commented redundant data directory cleanup here
# self.state_handler.remove_data_directory() # self.state_handler.remove_data_directory()
@@ -1121,17 +1150,20 @@ class Ha(object):
if not self.state_handler.is_running(): if not self.state_handler.is_running():
self.watchdog.disable() self.watchdog.disable()
if self.has_lock(): if self.has_lock():
self.state_handler.set_role('demoted') if self.state_handler.role in ('master', 'standby_leader'):
self.state_handler.set_role('demoted')
self._delete_leader() self._delete_leader()
return 'removed leader key after trying and failing to start postgres' return 'removed leader key after trying and failing to start postgres'
return 'failed to start postgres' return 'failed to start postgres'
self._crash_recovery_executed = False self._crash_recovery_executed = False
if self._rewind.executed and not self._rewind.failed:
self._rewind.reset_state()
return None return None
def cancel_initialization(self): def cancel_initialization(self):
logger.info('removing initialize key after failed attempt to bootstrap the cluster') logger.info('removing initialize key after failed attempt to bootstrap the cluster')
self.dcs.cancel_initialization() self.dcs.cancel_initialization()
self.state_handler.stop('immediate') self.state_handler.stop('immediate', stop_timeout=self.patroni.config['retry_timeout'])
self.state_handler.move_data_directory() self.state_handler.move_data_directory()
raise PatroniException('Failed to bootstrap cluster') raise PatroniException('Failed to bootstrap cluster')
@@ -1150,10 +1182,11 @@ class Ha(object):
return ret or 'running post_bootstrap' return ret or 'running post_bootstrap'
self.state_handler.bootstrapping = False self.state_handler.bootstrapping = False
self.dcs.set_config_value(json.dumps(self.patroni.config.dynamic_configuration, separators=(',', ':')))
if not self.watchdog.activate(): if not self.watchdog.activate():
logger.error('Cancelling bootstrap because watchdog activation failed') logger.error('Cancelling bootstrap because watchdog activation failed')
self.cancel_initialization() self.cancel_initialization()
self.dcs.initialize(create_new=(self.cluster.initialize is None), sysid=self.state_handler.sysid)
self.dcs.set_config_value(json.dumps(self.patroni.config.dynamic_configuration, separators=(',', ':')))
self.state_handler.slots_handler.sync_replication_slots(self.cluster) self.state_handler.slots_handler.sync_replication_slots(self.cluster)
self.dcs.take_leader() self.dcs.take_leader()
self.set_is_leader(True) self.set_is_leader(True)
@@ -1253,7 +1286,7 @@ class Ha(object):
# is data directory empty? # is data directory empty?
if self.state_handler.data_directory_empty(): if self.state_handler.data_directory_empty():
self.state_handler.set_role('uninitialized') self.state_handler.set_role('uninitialized')
self.state_handler.stop('immediate') self.state_handler.stop('immediate', stop_timeout=self.patroni.config['retry_timeout'])
# In case datadir went away while we were master. # In case datadir went away while we were master.
self.watchdog.disable() self.watchdog.disable()
@@ -1268,7 +1301,8 @@ class Ha(object):
data_sysid = self.state_handler.sysid data_sysid = self.state_handler.sysid
if not self.sysid_valid(data_sysid): if not self.sysid_valid(data_sysid):
# data directory is not empty, but no valid sysid, cluster must be broken, suggest reinit # data directory is not empty, but no valid sysid, cluster must be broken, suggest reinit
return "data dir for the cluster is not empty, but system ID is invalid; consider doing reinitalize" return ("data dir for the cluster is not empty, "
"but system ID is invalid; consider doing reinitialize")
if self.sysid_valid(self.cluster.initialize): if self.sysid_valid(self.cluster.initialize):
if self.cluster.initialize != data_sysid: if self.cluster.initialize != data_sysid:
@@ -1346,7 +1380,8 @@ class Ha(object):
# This might not be the desired behavior of users, as a graceful shutdown of the host can mean lost data. # This might not be the desired behavior of users, as a graceful shutdown of the host can mean lost data.
# We probably need to something smarter here. # We probably need to something smarter here.
disable_wd = self.watchdog.disable if self.watchdog.is_running else None disable_wd = self.watchdog.disable if self.watchdog.is_running else None
self.while_not_sync_standby(lambda: self.state_handler.stop(checkpoint=False, on_safepoint=disable_wd)) self.while_not_sync_standby(lambda: self.state_handler.stop(checkpoint=False, on_safepoint=disable_wd,
stop_timeout=self.master_stop_timeout()))
if not self.state_handler.is_running(): if not self.state_handler.is_running():
if self.has_lock(): if self.has_lock():
self.dcs.delete_leader() self.dcs.delete_leader()
+67 -24
View File
@@ -17,8 +17,9 @@ from patroni.postgresql.misc import parse_history, postgres_major_version_to_int
from patroni.postgresql.postmaster import PostmasterProcess from patroni.postgresql.postmaster import PostmasterProcess
from patroni.postgresql.slots import SlotsHandler from patroni.postgresql.slots import SlotsHandler
from patroni.exceptions import PostgresConnectionException from patroni.exceptions import PostgresConnectionException
from patroni.utils import Retry, RetryFailedError, polling_loop from patroni.utils import Retry, RetryFailedError, polling_loop, data_directory_is_empty, parse_int
from threading import current_thread, Lock from threading import current_thread, Lock
from psutil import TimeoutExpired
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -60,6 +61,7 @@ class Postgresql(object):
self._pending_restart = False self._pending_restart = False
self._connection = Connection() self._connection = Connection()
self.config = ConfigHandler(self, config) self.config = ConfigHandler(self, config)
self.config.check_directories()
self._bin_dir = config.get('bin_dir') or '' self._bin_dir = config.get('bin_dir') or ''
self.bootstrap = Bootstrap(self) self.bootstrap = Bootstrap(self)
@@ -133,6 +135,8 @@ class Postgresql(object):
@property @property
def cluster_info_query(self): def cluster_info_query(self):
pg_control_timeline = 'timeline_id FROM pg_catalog.pg_control_checkpoint()' \
if self._major_version >= 90600 and self.role == 'standby_leader' else '0'
return ("SELECT CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0 " return ("SELECT CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0 "
"ELSE ('x' || pg_catalog.substr(pg_catalog.pg_{0}file_name(" "ELSE ('x' || pg_catalog.substr(pg_catalog.pg_{0}file_name("
"pg_catalog.pg_current_{0}_{1}()), 1, 8))::bit(32)::int END, " "pg_catalog.pg_current_{0}_{1}()), 1, 8))::bit(32)::int END, "
@@ -141,7 +145,7 @@ class Postgresql(object):
"pg_catalog.pg_last_{0}_receive_{1}(), '0/0'), '0/0')::bigint," "pg_catalog.pg_last_{0}_receive_{1}(), '0/0'), '0/0')::bigint,"
" pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_last_{0}_replay_{1}(), '0/0')::bigint)" " pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_last_{0}_replay_{1}(), '0/0')::bigint)"
"ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), '0/0')::bigint " "ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), '0/0')::bigint "
"END").format(self.wal_name, self.lsn_name) "END, {2}").format(self.wal_name, self.lsn_name, pg_control_timeline)
def _version_file_exists(self): def _version_file_exists(self):
return not self.data_directory_empty() and os.path.isfile(self._version_file) return not self.data_directory_empty() and os.path.isfile(self._version_file)
@@ -263,9 +267,7 @@ class Postgresql(object):
def data_directory_empty(self): def data_directory_empty(self):
if self.pg_control_exists(): if self.pg_control_exists():
return False return False
if not os.path.exists(self._data_dir): return data_directory_is_empty(self._data_dir)
return True
return all(os.name != 'nt' and (n.startswith('.') or n == 'lost+found') for n in os.listdir(self._data_dir))
def replica_method_options(self, method): def replica_method_options(self, method):
return deepcopy(self.config.get(method, {})) return deepcopy(self.config.get(method, {}))
@@ -288,7 +290,7 @@ class Postgresql(object):
if not self._cluster_info_state: if not self._cluster_info_state:
try: try:
result = self._is_leader_retry(self._query, self.cluster_info_query).fetchone() result = self._is_leader_retry(self._query, self.cluster_info_query).fetchone()
self._cluster_info_state = dict(zip(['timeline', 'wal_position'], result)) self._cluster_info_state = dict(zip(['timeline', 'wal_position', 'pg_control_timeline'], result))
except RetryFailedError as e: # SELECT failed two times except RetryFailedError as e: # SELECT failed two times
self._cluster_info_state = {'error': str(e)} self._cluster_info_state = {'error': str(e)}
if not self.is_starting() and self.pg_isready() == STATE_REJECT: if not self.is_starting() and self.pg_isready() == STATE_REJECT:
@@ -302,6 +304,12 @@ class Postgresql(object):
def is_leader(self): def is_leader(self):
return bool(self._cluster_info_state_get('timeline')) 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 is_running(self): def is_running(self):
"""Returns PostmasterProcess if one is running on the data directory or None. If most recently seen process """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.""" is running updates the cached process based on pid file."""
@@ -406,7 +414,12 @@ class Postgresql(object):
self.set_state('starting') self.set_state('starting')
self._pending_restart = False self._pending_restart = False
configuration = self.config.effective_configuration try:
configuration = self.config.effective_configuration
except Exception:
return None
self.config.check_directories()
self.config.write_postgresql_conf(configuration) self.config.write_postgresql_conf(configuration)
self.config.resolve_connection_addresses() self.config.resolve_connection_addresses()
self.config.replace_pg_hba() self.config.replace_pg_hba()
@@ -450,11 +463,13 @@ class Postgresql(object):
else: else:
return None return None
def checkpoint(self, connect_kwargs=None): def checkpoint(self, connect_kwargs=None, timeout=None):
check_not_is_in_recovery = connect_kwargs is not None check_not_is_in_recovery = connect_kwargs is not None
connect_kwargs = connect_kwargs or self.config.local_connect_kwargs connect_kwargs = connect_kwargs or self.config.local_connect_kwargs
for p in ['connect_timeout', 'options']: for p in ['connect_timeout', 'options']:
connect_kwargs.pop(p, None) connect_kwargs.pop(p, None)
if timeout:
connect_kwargs['connect_timeout'] = timeout
try: try:
with get_connection_cursor(**connect_kwargs) as cur: with get_connection_cursor(**connect_kwargs) as cur:
cur.execute("SET statement_timeout = 0") cur.execute("SET statement_timeout = 0")
@@ -467,7 +482,7 @@ class Postgresql(object):
logger.exception('Exception during CHECKPOINT') logger.exception('Exception during CHECKPOINT')
return 'not accessible or not healty' return 'not accessible or not healty'
def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None): def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None, stop_timeout=None):
"""Stop PostgreSQL """Stop PostgreSQL
Supports a callback when a safepoint is reached. A safepoint is when no user backend can return a successful Supports a callback when a safepoint is reached. A safepoint is when no user backend can return a successful
@@ -479,7 +494,7 @@ class Postgresql(object):
if checkpoint is None: if checkpoint is None:
checkpoint = False if mode == 'immediate' else True checkpoint = False if mode == 'immediate' else True
success, pg_signaled = self._do_stop(mode, block_callbacks, checkpoint, on_safepoint) success, pg_signaled = self._do_stop(mode, block_callbacks, checkpoint, on_safepoint, stop_timeout)
if success: if success:
# block_callbacks is used during restart to avoid # block_callbacks is used during restart to avoid
# running start/stop callbacks in addition to restart ones # running start/stop callbacks in addition to restart ones
@@ -492,7 +507,7 @@ class Postgresql(object):
self.set_state('stop failed') self.set_state('stop failed')
return success return success
def _do_stop(self, mode, block_callbacks, checkpoint, on_safepoint): def _do_stop(self, mode, block_callbacks, checkpoint, on_safepoint, stop_timeout):
postmaster = self.is_running() postmaster = self.is_running()
if not postmaster: if not postmaster:
if on_safepoint: if on_safepoint:
@@ -500,13 +515,13 @@ class Postgresql(object):
return True, False return True, False
if checkpoint and not self.is_starting(): if checkpoint and not self.is_starting():
self.checkpoint() self.checkpoint(timeout=stop_timeout)
if not block_callbacks: if not block_callbacks:
self.set_state('stopping') self.set_state('stopping')
# Send signal to postmaster to stop # Send signal to postmaster to stop
success = postmaster.signal_stop(mode) success = postmaster.signal_stop(mode, self.pgcommand('pg_ctl'))
if success is not None: if success is not None:
if success and on_safepoint: if success and on_safepoint:
on_safepoint() on_safepoint()
@@ -519,15 +534,32 @@ class Postgresql(object):
postmaster.wait_for_user_backends_to_close() postmaster.wait_for_user_backends_to_close()
on_safepoint() on_safepoint()
postmaster.wait() 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 return True, True
@staticmethod def terminate_postmaster(self, postmaster, mode, stop_timeout):
def terminate_starting_postmaster(postmaster): 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 """Terminates a postmaster that has not yet opened ports or possibly even written a pid file. Blocks
until the process goes away.""" until the process goes away."""
postmaster.signal_stop('immediate') postmaster.signal_stop('immediate', self.pgcommand('pg_ctl'))
postmaster.wait() postmaster.wait()
def _wait_for_connection_close(self, postmaster): def _wait_for_connection_close(self, postmaster):
@@ -632,7 +664,7 @@ class Postgresql(object):
data = subprocess.check_output([self.pgcommand('pg_controldata'), self._data_dir], env=env) data = subprocess.check_output([self.pgcommand('pg_controldata'), self._data_dir], env=env)
if data: if data:
data = data.decode('utf-8').splitlines() data = data.decode('utf-8').splitlines()
# pg_controldata output depends on major verion. Some of parameters are prefixed by 'Current ' # pg_controldata output depends on major version. Some of parameters are prefixed by 'Current '
result = {l.split(':')[0].replace('Current ', '', 1): l.split(':', 1)[1].strip() for l in data result = {l.split(':')[0].replace('Current ', '', 1): l.split(':', 1)[1].strip() for l in data
if l and ':' in l} if l and ':' in l}
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
@@ -640,10 +672,10 @@ class Postgresql(object):
return result return result
@contextmanager @contextmanager
def get_replication_connection_cursor(self, host='localhost', port=5432, database=None, **kwargs): def get_replication_connection_cursor(self, host='localhost', port=5432, **kwargs):
conn_kwargs = self.config.replication.copy() conn_kwargs = self.config.replication.copy()
conn_kwargs.update(host=host, port=int(port), database=database or self._database, connect_timeout=3, conn_kwargs.update(host=host, port=int(port) if port else None, user=conn_kwargs.pop('username'),
user=conn_kwargs.pop('username'), replication=1, options='-c statement_timeout=2000') connect_timeout=3, replication=1, options='-c statement_timeout=2000')
with get_connection_cursor(**conn_kwargs) as cur: with get_connection_cursor(**conn_kwargs) as cur:
yield cur yield cur
@@ -733,11 +765,13 @@ class Postgresql(object):
# This method could be called from different threads (simultaneously with some other `_query` calls). # 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 it is called not from main thread we will create a new cursor to execute statement.
if current_thread().ident == self.__thread_ident: if current_thread().ident == self.__thread_ident:
return self._cluster_info_state_get('timeline'), self._cluster_info_state_get('wal_position') return (self._cluster_info_state_get('timeline'),
self._cluster_info_state_get('wal_position'),
self._cluster_info_state_get('pg_control_timeline'))
with self.connection().cursor() as cursor: with self.connection().cursor() as cursor:
cursor.execute(self.cluster_info_query) cursor.execute(self.cluster_info_query)
return cursor.fetchone()[:2] return cursor.fetchone()[:3]
def postmaster_start_time(self): def postmaster_start_time(self):
try: try:
@@ -787,6 +821,15 @@ class Postgresql(object):
pg_wal_realpath = os.path.realpath(pg_wal_path) pg_wal_realpath = os.path.realpath(pg_wal_path)
logger.info('Removing WAL directory: %s', pg_wal_realpath) logger.info('Removing WAL directory: %s', pg_wal_realpath)
shutil.rmtree(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) shutil.rmtree(self._data_dir)
except (IOError, OSError): except (IOError, OSError):
@@ -815,7 +858,7 @@ class Postgresql(object):
if state != 'streaming' or not member or member.tags.get('nosync', False): if state != 'streaming' or not member or member.tags.get('nosync', False):
continue continue
if sync_state == 'sync': if sync_state == 'sync':
return app_name, True return member.name, True
if sync_state == 'potential' and app_name == current: if sync_state == 'potential' and app_name == current:
# Prefer current even if not the best one any more to avoid indecisivness and spurious swaps. # Prefer current even if not the best one any more to avoid indecisivness and spurious swaps.
return cluster.sync.sync_standby, False return cluster.sync.sync_standby, False
+13 -12
View File
@@ -5,9 +5,8 @@ import tempfile
import time import time
from patroni.dcs import RemoteMember from patroni.dcs import RemoteMember
from patroni.utils import deep_compare, uri from patroni.utils import deep_compare
from six import string_types from six import string_types
from six.moves.urllib.parse import quote_plus
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -123,19 +122,13 @@ class Bootstrap(object):
cmd = config.get('post_bootstrap') or config.get('post_init') cmd = config.get('post_bootstrap') or config.get('post_init')
if cmd: if cmd:
r = self._postgresql.config.local_connect_kwargs r = self._postgresql.config.local_connect_kwargs
connstring = self._postgresql.config.format_dsn(r, True)
if 'host' in r: if 'host' not in r:
# '/tmp' => '%2Ftmp' for unix socket path
host = quote_plus(r['host']) if r['host'].startswith('/') else r['host']
else:
host = ''
# https://www.postgresql.org/docs/current/static/libpq-pgpass.html # 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 # 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. # (pghost empty or the default socket directory) connections coming from the local machine.
r['host'] = 'localhost' # set it to localhost to write into pgpass r['host'] = 'localhost' # set it to localhost to write into pgpass
connstring = uri('postgres', (host, r['port']), r['database'], r.get('user'))
env = self._postgresql.config.write_pgpass(r) if 'password' in r else None env = self._postgresql.config.write_pgpass(r) if 'password' in r else None
try: try:
@@ -168,9 +161,9 @@ class Bootstrap(object):
if clone_member and clone_member.conn_url: if clone_member and clone_member.conn_url:
r = clone_member.conn_kwargs(self._postgresql.config.replication) r = clone_member.conn_kwargs(self._postgresql.config.replication)
connstring = uri('postgres', (r['host'], r['port']), r['database'], r['user'])
# add the credentials to connect to the replica origin to pgpass. # add the credentials to connect to the replica origin to pgpass.
env = self._postgresql.config.write_pgpass(r) env = self._postgresql.config.write_pgpass(r)
connstring = self._postgresql.config.format_dsn(r, True)
else: else:
connstring = '' connstring = ''
env = os.environ.copy() env = os.environ.copy()
@@ -317,7 +310,15 @@ BEGIN
CREATE ROLE "{0}" WITH {1}; CREATE ROLE "{0}" WITH {1};
END IF; END IF;
END;$$""".format(name, ' '.join(options)) END;$$""".format(name, ' '.join(options))
self._postgresql.query(sql, *params) 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): def post_bootstrap(self, config, task):
try: try:
+63 -30
View File
@@ -6,11 +6,13 @@ import socket
import stat import stat
import time import time
from patroni.exceptions import PatroniException
from six.moves.urllib_parse import urlparse, parse_qsl, unquote from six.moves.urllib_parse import urlparse, parse_qsl, unquote
from urllib3.response import HTTPHeaderDict from urllib3.response import HTTPHeaderDict
from ..dcs import slot_name_from_member_name, RemoteMember from ..dcs import slot_name_from_member_name, RemoteMember
from ..utils import compare_values, parse_bool, parse_int, split_host_port, uri from ..utils import compare_values, parse_bool, parse_int, split_host_port, uri, \
validate_directory, is_subpath
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -333,7 +335,10 @@ class ConfigHandler(object):
self._standby_signal = os.path.join(postgresql.data_dir, 'standby.signal') self._standby_signal = os.path.join(postgresql.data_dir, 'standby.signal')
self._auto_conf = os.path.join(postgresql.data_dir, 'postgresql.auto.conf') self._auto_conf = os.path.join(postgresql.data_dir, 'postgresql.auto.conf')
self._auto_conf_mtime = None self._auto_conf_mtime = None
self._pgpass = config.get('pgpass') or os.path.join(os.path.expanduser('~'), 'pgpass') self._pgpass = os.path.abspath(config.get('pgpass') or os.path.join(os.path.expanduser('~'), 'pgpass'))
if os.path.exists(self._pgpass) and not os.path.isfile(self._pgpass):
raise PatroniException("'{}' exists and it's not a file, check your `postgresql.pgpass` configuration"
.format(self._pgpass))
self._passfile = None self._passfile = None
self._passfile_mtime = None self._passfile_mtime = None
self._synchronous_standby_names = None self._synchronous_standby_names = None
@@ -347,6 +352,21 @@ class ConfigHandler(object):
self._server_parameters = self.get_server_parameters(self._config) self._server_parameters = self.get_server_parameters(self._config)
self._adjust_recovery_parameters() self._adjust_recovery_parameters()
def try_to_create_dir(self, d, msg):
d = os.path.join(self._postgresql._data_dir, d)
if (not is_subpath(self._postgresql._data_dir, d) or not self._postgresql.data_directory_empty()):
validate_directory(d, msg)
def check_directories(self):
if "unix_socket_directories" in self._server_parameters:
for d in self._server_parameters["unix_socket_directories"].split(","):
self.try_to_create_dir(d.strip(), "'{}' is defined in unix_socket_directories, {}")
if "stats_temp_directory" in self._server_parameters:
self.try_to_create_dir(self._server_parameters["stats_temp_directory"],
"'{}' is defined in stats_temp_directory, {}")
self.try_to_create_dir(os.path.dirname(self._pgpass),
"'{}' is defined in `postgresql.pgpass`, {}")
@property @property
def _configuration_to_save(self): def _configuration_to_save(self):
configuration = [os.path.basename(self._postgresql_conf)] configuration = [os.path.basename(self._postgresql_conf)]
@@ -436,7 +456,7 @@ class ConfigHandler(object):
# when we are doing custom bootstrap we assume that we don't know superuser password # when we are doing custom bootstrap we assume that we don't know superuser password
# and in order to be able to change it, we are opening trust access from a certain address # and in order to be able to change it, we are opening trust access from a certain address
if self._postgresql.bootstrap.running_custom_bootstrap: if self._postgresql.bootstrap.running_custom_bootstrap:
addresses = {'': 'local'} addresses = {} if os.name == 'nt' else {'': 'local'} # windows doesn't yet support unix-domain sockets
if 'host' in self.local_replication_address and not self.local_replication_address['host'].startswith('/'): if 'host' in self.local_replication_address and not self.local_replication_address['host'].startswith('/'):
addresses.update({sa[0] + '/32': 'host' for _, _, _, _, sa in socket.getaddrinfo( addresses.update({sa[0] + '/32': 'host' for _, _, _, _, sa in socket.getaddrinfo(
self.local_replication_address['host'], self.local_replication_address['port'], self.local_replication_address['host'], self.local_replication_address['port'],
@@ -480,17 +500,22 @@ class ConfigHandler(object):
def format_dsn(self, params, include_dbname=False): def format_dsn(self, params, include_dbname=False):
# A list of keywords that can be found in a conninfo string. Follows what is acceptable by libpq # A list of keywords that can be found in a conninfo string. Follows what is acceptable by libpq
keywords = ('user', 'passfile' if params.get('passfile') else 'password', 'host', 'port', 'sslmode', keywords = ('dbname', 'user', 'passfile' if params.get('passfile') else 'password', 'host', 'port', 'sslmode',
'sslcompression', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'application_name', 'krbsrvname') 'sslcompression', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'application_name', 'krbsrvname')
if include_dbname: if include_dbname:
params = params.copy() params = params.copy()
params['dbname'] = params.get('database') or self._postgresql.database params['dbname'] = params.get('database') or self._postgresql.database
keywords = ('dbname',) + keywords # we are abusing information about the necessity of dbname
# dsn should contain passfile or password only if there is no dbname in it (it is used in recovery.conf)
skip = {'passfile', 'password'}
else:
skip = {'dbname'}
def escape(value): def escape(value):
return re.sub(r'([\'\\ ])', r'\\\1', str(value)) return re.sub(r'([\'\\ ])', r'\\\1', str(value))
return ' '.join('{0}={1}'.format(kw, escape(params[kw])) for kw in keywords if params.get(kw) is not None) return ' '.join('{0}={1}'.format(kw, escape(params[kw])) for kw in keywords
if kw not in skip and params.get(kw) is not None)
def _write_recovery_params(self, fd, recovery_params): def _write_recovery_params(self, fd, recovery_params):
for name, value in sorted(recovery_params.items()): for name, value in sorted(recovery_params.items()):
@@ -516,15 +541,16 @@ class ConfigHandler(object):
is_remote_master = isinstance(member, RemoteMember) is_remote_master = isinstance(member, RemoteMember)
primary_conninfo = self.primary_conninfo_params(member) primary_conninfo = self.primary_conninfo_params(member)
if primary_conninfo: if primary_conninfo:
use_slots = self.get('use_slots', True) and self._postgresql.major_version >= 90400
if use_slots and not (is_remote_master and member.no_replication_slot):
primary_slot_name = member.primary_slot_name if is_remote_master else self._postgresql.name
recovery_params['primary_slot_name'] = slot_name_from_member_name(primary_slot_name)
recovery_params['primary_conninfo'] = primary_conninfo recovery_params['primary_conninfo'] = primary_conninfo
if self.get('use_slots', True) and self._postgresql.major_version >= 90400 \
and not (is_remote_master and member.no_replication_slot):
recovery_params['primary_slot_name'] = member.primary_slot_name if is_remote_master \
else slot_name_from_member_name(self._postgresql.name)
if is_remote_master: # standby_cluster config might have different parameters, we want to override them # standby_cluster config might have different parameters, we want to override them
recovery_params.update({p: member.data.get(p) for p in ('restore_command', 'recovery_min_apply_delay', standby_cluster_params = ['restore_command', 'archive_cleanup_command']\
'archive_cleanup_command') if member.data.get(p)}) + (['recovery_min_apply_delay'] if is_remote_master else [])
recovery_params.update({p: member.data.get(p) for p in standby_cluster_params if member and member.data.get(p)})
return recovery_params return recovery_params
def recovery_conf_exists(self): def recovery_conf_exists(self):
@@ -559,7 +585,7 @@ class ConfigHandler(object):
try: try:
values = self._get_pg_settings(self._recovery_parameters_to_compare).values() values = self._get_pg_settings(self._recovery_parameters_to_compare).values()
values = {p[0]: [p[1], p[4] == 'postmaster'] for p in values} values = {p[0]: [p[1], p[4] == 'postmaster', p[5]] for p in values}
self._postgresql_conf_mtime = pg_conf_mtime self._postgresql_conf_mtime = pg_conf_mtime
self._auto_conf_mtime = auto_conf_mtime self._auto_conf_mtime = auto_conf_mtime
self._postmaster_ctime = postmaster_ctime self._postmaster_ctime = postmaster_ctime
@@ -588,6 +614,7 @@ class ConfigHandler(object):
values[match.group(1)] = [value, True] values[match.group(1)] = [value, True]
self._recovery_conf_mtime = recovery_conf_mtime self._recovery_conf_mtime = recovery_conf_mtime
values.setdefault('recovery_min_apply_delay', ['0', True]) values.setdefault('recovery_min_apply_delay', ['0', True])
values['recovery_min_apply_delay'][0] = parse_int(values['recovery_min_apply_delay'][0], 'ms')
values.update({param: ['', True] for param in self._recovery_parameters_to_compare if param not in values}) values.update({param: ['', True] for param in self._recovery_parameters_to_compare if param not in values})
return values, True return values, True
@@ -625,7 +652,7 @@ class ConfigHandler(object):
else: else:
return False return False
return all(primary_conninfo.get(p) == str(v) for p, v in wanted_primary_conninfo.items()) return all(primary_conninfo.get(p) == str(v) for p, v in wanted_primary_conninfo.items() if v is not None)
def check_recovery_conf(self, member): def check_recovery_conf(self, member):
"""Returns a tuple. The first boolean element indicates that recovery params don't match """Returns a tuple. The first boolean element indicates that recovery params don't match
@@ -668,6 +695,12 @@ class ConfigHandler(object):
wanted_recovery_params = self.build_recovery_params(member) wanted_recovery_params = self.build_recovery_params(member)
for param, value in self._current_recovery_params.items(): for param, value in self._current_recovery_params.items():
# Skip certain parameters defined in the included postgres config files
# if we know that they are not specified in the patroni configuration.
if len(value) > 2 and value[2] not in (self._postgresql_conf, self._auto_conf) and \
param in ('archive_cleanup_command', 'promote_trigger_file', 'recovery_end_command',
'recovery_min_apply_delay', 'restore_command') and param not in wanted_recovery_params:
continue
if param == 'recovery_min_apply_delay': if param == 'recovery_min_apply_delay':
if not compare_values('integer', 'ms', value[0], wanted_recovery_params.get(param, 0)): if not compare_values('integer', 'ms', value[0], wanted_recovery_params.get(param, 0)):
record_missmatch(value[1]) record_missmatch(value[1])
@@ -837,7 +870,7 @@ class ConfigHandler(object):
self._postgresql.set_connection_kwargs(self.local_connect_kwargs) self._postgresql.set_connection_kwargs(self.local_connect_kwargs)
def _get_pg_settings(self, names): def _get_pg_settings(self, names):
return {r[0]: r for r in self._postgresql.query(('SELECT name, setting, unit, vartype, context ' return {r[0]: r for r in self._postgresql.query(('SELECT name, setting, unit, vartype, context, sourcefile'
+ ' FROM pg_catalog.pg_settings ' + + ' FROM pg_catalog.pg_settings ' +
' WHERE pg_catalog.lower(name) = ANY(%s)'), ' WHERE pg_catalog.lower(name) = ANY(%s)'),
[n.lower() for n in names])} [n.lower() for n in names])}
@@ -866,9 +899,9 @@ class ConfigHandler(object):
conf_changed = hba_changed = ident_changed = local_connection_address_changed = pending_restart = False conf_changed = hba_changed = ident_changed = local_connection_address_changed = pending_restart = False
if self._postgresql.state == 'running': if self._postgresql.state == 'running':
changes = CaseInsensitiveDict({p: v for p, v in server_parameters.items() changes = CaseInsensitiveDict({p: v for p, v in server_parameters.items()
if '.' not in p and p.lower() not in self._RECOVERY_PARAMETERS}) if p.lower() not in self._RECOVERY_PARAMETERS})
changes.update({p: None for p in self._server_parameters.keys() changes.update({p: None for p in self._server_parameters.keys()
if not ('.' in p or p in changes or p.lower() in self._RECOVERY_PARAMETERS)}) if not (p in changes or p.lower() in self._RECOVERY_PARAMETERS)})
if changes: if changes:
if 'wal_buffers' in changes: # we need to calculate the default value of wal_buffers if 'wal_buffers' in changes: # we need to calculate the default value of wal_buffers
undef = [p for p in ('shared_buffers', 'wal_segment_size', 'wal_block_size') if p not in changes] undef = [p for p in ('shared_buffers', 'wal_segment_size', 'wal_block_size') if p not in changes]
@@ -894,21 +927,17 @@ class ConfigHandler(object):
local_connection_address_changed = True local_connection_address_changed = True
else: else:
logger.info('Changed %s from %s to %s', r[0], r[1], new_value) logger.info('Changed %s from %s to %s', r[0], r[1], new_value)
for param in changes: for param, value in changes.items():
if param in server_parameters: if '.' in param:
# Check that user-defined-paramters have changed (parameters with period in name)
if value is None or param not in self._server_parameters \
or str(value) != str(self._server_parameters[param]):
logger.info('Changed %s from %s to %s', param, self._server_parameters.get(param), value)
conf_changed = True
elif param in server_parameters:
logger.warning('Removing invalid parameter `%s` from postgresql.parameters', param) logger.warning('Removing invalid parameter `%s` from postgresql.parameters', param)
server_parameters.pop(param) server_parameters.pop(param)
# Check that user-defined-paramters have changed (parameters with period in name)
for p, v in server_parameters.items():
if '.' in p and (p not in self._server_parameters or str(v) != str(self._server_parameters[p])):
logger.info('Changed %s from %s to %s', p, self._server_parameters.get(p), v)
conf_changed = True
for p, v in self._server_parameters.items():
if '.' in p and (p not in server_parameters or str(v) != str(server_parameters[p])):
logger.info('Changed %s from %s to %s', p, v, server_parameters.get(p))
conf_changed = True
if not server_parameters.get('hba_file') and config.get('pg_hba'): if not server_parameters.get('hba_file') and config.get('pg_hba'):
hba_changed = self._config.get('pg_hba', []) != config['pg_hba'] hba_changed = self._config.get('pg_hba', []) != config['pg_hba']
@@ -996,6 +1025,10 @@ class ConfigHandler(object):
for name, cname in options_mapping.items(): for name, cname in options_mapping.items():
value = parse_int(effective_configuration[name]) value = parse_int(effective_configuration[name])
if cname not in data:
logger.warning('%s is missing from pg_controldata output', cname)
continue
cvalue = parse_int(data[cname]) cvalue = parse_int(data[cname])
if cvalue > value: if cvalue > value:
effective_configuration[name] = cvalue effective_configuration[name] = cvalue
+56 -7
View File
@@ -7,7 +7,7 @@ import signal
import subprocess import subprocess
import sys import sys
from patroni import PATRONI_ENV_PREFIX from patroni import PATRONI_ENV_PREFIX, KUBERNETES_ENV_PREFIX
# avoid spawning the resource tracker process # avoid spawning the resource tracker process
if sys.version_info >= (3, 8): # pragma: no cover if sys.version_info >= (3, 8): # pragma: no cover
@@ -20,9 +20,9 @@ elif sys.version_info >= (3, 4): # pragma: no cover
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
STOP_SIGNALS = { STOP_SIGNALS = {
'smart': signal.SIGTERM, 'smart': 'TERM',
'fast': signal.SIGINT, 'fast': 'INT',
'immediate': signal.SIGQUIT if os.name != 'nt' else signal.SIGABRT, 'immediate': 'QUIT',
} }
@@ -105,7 +105,43 @@ class PostmasterProcess(psutil.Process):
except psutil.NoSuchProcess: except psutil.NoSuchProcess:
return None return None
def signal_stop(self, mode): 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 """Signal postmaster process to stop
:returns None if signaled, True if process is already gone, False if error :returns None if signaled, True if process is already gone, False if error
@@ -113,8 +149,10 @@ class PostmasterProcess(psutil.Process):
if self.is_single_user: if self.is_single_user:
logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid)) logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid))
return False return False
if os.name != 'posix':
return self.pg_ctl_kill(mode, pg_ctl)
try: try:
self.send_signal(STOP_SIGNALS[mode]) self.send_signal(getattr(signal, 'SIG' + STOP_SIGNALS[mode]))
except psutil.NoSuchProcess: except psutil.NoSuchProcess:
return True return True
except psutil.AccessDenied as e: except psutil.AccessDenied as e:
@@ -123,6 +161,16 @@ class PostmasterProcess(psutil.Process):
return None 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): def wait_for_user_backends_to_close(self):
# These regexps are cross checked against versions PostgreSQL 9.1 .. 11 # These regexps are cross checked against versions PostgreSQL 9.1 .. 11
aux_proc_re = re.compile("(?:postgres:)( .*:)? (?:(?:archiver|startup|autovacuum launcher|autovacuum worker|" aux_proc_re = re.compile("(?:postgres:)( .*:)? (?:(?:archiver|startup|autovacuum launcher|autovacuum worker|"
@@ -164,7 +212,8 @@ class PostmasterProcess(psutil.Process):
# In order to make everything portable we can't use fork&exec approach here, so we will call # 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. # 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. # 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)} 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: try:
proc = PostmasterProcess._from_pidfile(data_dir) proc = PostmasterProcess._from_pidfile(data_dir)
if proc and not proc._is_postmaster_process(): if proc and not proc._is_postmaster_process():
+34 -10
View File
@@ -2,9 +2,12 @@ import logging
import os import os
import subprocess import subprocess
from patroni.dcs import Leader from threading import Lock, Thread
from patroni.postgresql.connection import get_connection_cursor
from patroni.postgresql.misc import parse_history, parse_lsn 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__) logger = logging.getLogger(__name__)
@@ -16,6 +19,7 @@ class Rewind(object):
def __init__(self, postgresql): def __init__(self, postgresql):
self._postgresql = postgresql self._postgresql = postgresql
self._checkpoint_task_lock = Lock()
self.reset_state() self.reset_state()
@staticmethod @staticmethod
@@ -131,14 +135,32 @@ class Rewind(object):
self._check_timeline_and_lsn(leader) self._check_timeline_and_lsn(leader)
return leader and leader.conn_url and self._state == REWIND_STATUS.NEED return leader and leader.conn_url and self._state == REWIND_STATUS.NEED
def check_for_checkpoint_after_promote(self): def __checkpoint(self, task):
try:
result = self._postgresql.checkpoint()
except Exception as e:
result = 'Exception: ' + str(e)
with task:
task.complete(not bool(result))
def ensure_checkpoint_after_promote(self):
"""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(): if self._state == REWIND_STATUS.INITIAL and self._postgresql.is_leader():
try: with self._checkpoint_task_lock:
timeline = int(self._postgresql.controldata().get("Latest checkpoint's TimeLineID")) if self._checkpoint_task:
if self._postgresql.get_master_timeline() == timeline: with self._checkpoint_task:
self._state = REWIND_STATUS.CHECKPOINT if self._checkpoint_task.result:
except (TypeError, ValueError): self._state = REWIND_STATUS.CHECKPOINT
logger.exception('Failed to parse timeline from pg_controldata output') if self._checkpoint_task.result is not False:
return
else:
self._checkpoint_task = CriticalTask()
return Thread(target=self.__checkpoint, args=(self._checkpoint_task,)).start()
if self._postgresql.get_master_timeline() == self._postgresql.pg_control_timeline():
self._state = REWIND_STATUS.CHECKPOINT
def checkpoint_after_promote(self): def checkpoint_after_promote(self):
return self._state == REWIND_STATUS.CHECKPOINT return self._state == REWIND_STATUS.CHECKPOINT
@@ -195,6 +217,8 @@ class Rewind(object):
def reset_state(self): def reset_state(self):
self._state = REWIND_STATUS.INITIAL self._state = REWIND_STATUS.INITIAL
with self._checkpoint_task_lock:
self._checkpoint_task = None
@property @property
def is_needed(self): def is_needed(self):
+38 -3
View File
@@ -1,7 +1,9 @@
import logging import logging
import os
import platform import platform
import random import random
import re import re
import tempfile
import time import time
from dateutil import tz from dateutil import tz
@@ -332,7 +334,7 @@ class Retry(object):
logger.warning('Retry got exception: %s', e) logger.warning('Retry got exception: %s', e)
raise RetryFailedError("Too many retry attempts") raise RetryFailedError("Too many retry attempts")
self._attempts += 1 self._attempts += 1
sleeptime = self.sleeptime sleeptime = hasattr(e, 'sleeptime') and e.sleeptime or self.sleeptime
if self._cur_stoptime is not None and time.time() + sleeptime >= self._cur_stoptime: if self._cur_stoptime is not None and time.time() + sleeptime >= self._cur_stoptime:
logger.warning('Retry got exception: %s', e) logger.warning('Retry got exception: %s', e)
@@ -388,9 +390,12 @@ def cluster_as_json(cluster):
else: else:
role = 'replica' role = 'replica'
member = {'name': m.name, 'role': role, 'state': m.data.get('state', ''), 'api_url': m.api_url}
conn_kwargs = m.conn_kwargs() conn_kwargs = m.conn_kwargs()
member = {'name': m.name, 'host': conn_kwargs['host'], 'port': int(conn_kwargs['port']), if conn_kwargs.get('host'):
'role': role, 'state': m.data.get('state', ''), 'api_url': m.api_url} member['host'] = conn_kwargs['host']
if conn_kwargs.get('port'):
member['port'] = int(conn_kwargs['port'])
optional_attributes = ('timeline', 'pending_restart', 'scheduled_restart', 'tags') optional_attributes = ('timeline', 'pending_restart', 'scheduled_restart', 'tags')
member.update({n: m.data[n] for n in optional_attributes if n in m.data}) member.update({n: m.data[n] for n in optional_attributes if n in m.data})
@@ -416,3 +421,33 @@ def cluster_as_json(cluster):
if cluster.failover.candidate: if cluster.failover.candidate:
ret['scheduled_switchover']['to'] = cluster.failover.candidate ret['scheduled_switchover']['to'] = cluster.failover.candidate
return ret 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))
+379
View File
@@ -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
View File
@@ -1 +1 @@
__version__ = '1.6.2' __version__ = '1.6.5'
-1
View File
@@ -7,7 +7,6 @@ python-etcd>=0.4.3,<0.5
python-consul>=0.7.1 python-consul>=0.7.1
click>=4.1 click>=4.1
prettytable>=0.7 prettytable>=0.7
tzlocal
python-dateutil python-dateutil
psutil>=2.0.0 psutil>=2.0.0
cdiff cdiff
+5 -2
View File
@@ -66,6 +66,7 @@ class MockPostmaster(object):
self.wait_for_user_backends_to_close = Mock() self.wait_for_user_backends_to_close = Mock()
self.signal_stop = Mock(return_value=None) self.signal_stop = Mock(return_value=None)
self.wait = Mock() self.wait = Mock()
self.signal_kill = Mock(return_value=False)
class MockCursor(object): class MockCursor(object):
@@ -75,6 +76,7 @@ class MockCursor(object):
self.closed = False self.closed = False
self.rowcount = 0 self.rowcount = 0
self.results = [] self.results = []
self.description = [Mock()]
def execute(self, sql, *params): def execute(self, sql, *params):
if sql.startswith('blabla'): if sql.startswith('blabla'):
@@ -86,7 +88,7 @@ class MockCursor(object):
elif sql.startswith('SELECT slot_name'): elif sql.startswith('SELECT slot_name'):
self.results = [('blabla', 'physical'), ('foobar', 'physical'), ('ls', 'logical', 'a', 'b')] self.results = [('blabla', 'physical'), ('foobar', 'physical'), ('ls', 'logical', 'a', 'b')]
elif sql.startswith('SELECT CASE WHEN pg_catalog.pg_is_in_recovery()'): elif sql.startswith('SELECT CASE WHEN pg_catalog.pg_is_in_recovery()'):
self.results = [(1, 2)] self.results = [(1, 2, 1)]
elif sql.startswith('SELECT pg_catalog.pg_is_in_recovery()'): elif sql.startswith('SELECT pg_catalog.pg_is_in_recovery()'):
self.results = [(False, 2)] self.results = [(False, 2)]
elif sql.startswith('SELECT pg_catalog.to_char'): elif sql.startswith('SELECT pg_catalog.to_char'):
@@ -164,7 +166,8 @@ class PostgresInit(unittest.TestCase):
'search_path': 'public', 'hot_standby': 'on', 'max_wal_senders': 5, 'search_path': 'public', 'hot_standby': 'on', 'max_wal_senders': 5,
'wal_keep_segments': 8, 'wal_log_hints': 'on', 'max_locks_per_transaction': 64, 'wal_keep_segments': 8, 'wal_log_hints': 'on', 'max_locks_per_transaction': 64,
'max_worker_processes': 8, 'max_connections': 100, 'max_prepared_transactions': 0, 'max_worker_processes': 8, 'max_connections': 100, 'max_prepared_transactions': 0,
'track_commit_timestamp': 'off', 'unix_socket_directories': '/tmp', 'trigger_file': 'bla'} 'track_commit_timestamp': 'off', 'unix_socket_directories': '/tmp', 'trigger_file': 'bla',
'stats_temp_directory': '/tmp'}
@patch('psycopg2.connect', psycopg2_connect) @patch('psycopg2.connect', psycopg2_connect)
@patch.object(ConfigHandler, 'write_postgresql_conf', Mock()) @patch.object(ConfigHandler, 'write_postgresql_conf', Mock())
+2 -2
View File
@@ -209,13 +209,13 @@ class TestBootstrap(BaseTestPostgresql):
mock_cancellable_subprocess_call.assert_called() mock_cancellable_subprocess_call.assert_called()
args, kwargs = mock_cancellable_subprocess_call.call_args args, kwargs = mock_cancellable_subprocess_call.call_args
self.assertTrue('PGPASSFILE' in kwargs['env']) self.assertTrue('PGPASSFILE' in kwargs['env'])
self.assertEqual(args[0], ['/bin/false', 'postgres://127.0.0.2:5432/postgres']) self.assertEqual(args[0], ['/bin/false', 'dbname=postgres host=127.0.0.2 port=5432'])
mock_cancellable_subprocess_call.reset_mock() mock_cancellable_subprocess_call.reset_mock()
self.p.config._local_address.pop('host') self.p.config._local_address.pop('host')
self.assertTrue(self.b.call_post_bootstrap({'post_init': '/bin/false'})) self.assertTrue(self.b.call_post_bootstrap({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.assert_called() mock_cancellable_subprocess_call.assert_called()
self.assertEqual(mock_cancellable_subprocess_call.call_args[0][0], ['/bin/false', 'postgres://:5432/postgres']) self.assertEqual(mock_cancellable_subprocess_call.call_args[0][0], ['/bin/false', 'dbname=postgres port=5432'])
mock_cancellable_subprocess_call.side_effect = OSError mock_cancellable_subprocess_call.side_effect = OSError
self.assertFalse(self.b.call_post_bootstrap({'post_init': '/bin/false'})) self.assertFalse(self.b.call_post_bootstrap({'post_init': '/bin/false'}))
+30 -18
View File
@@ -7,7 +7,7 @@ from datetime import datetime, timedelta
from mock import patch, Mock from mock import patch, Mock
from patroni.ctl import ctl, store_config, load_config, output_members, get_dcs, parse_dcs, \ from patroni.ctl import ctl, store_config, load_config, output_members, get_dcs, parse_dcs, \
get_all_members, get_any_member, get_cursor, query_member, configure, PatroniCtlException, apply_config_changes, \ get_all_members, get_any_member, get_cursor, query_member, configure, PatroniCtlException, apply_config_changes, \
format_config_for_editing, show_diff, invoke_editor, format_pg_version, find_executable format_config_for_editing, show_diff, invoke_editor, format_pg_version, find_executable, CONFIG_FILE_PATH
from patroni.dcs.etcd import Client, Failover from patroni.dcs.etcd import Client, Failover
from patroni.utils import tzutc from patroni.utils import tzutc
from psycopg2 import OperationalError from psycopg2 import OperationalError
@@ -18,22 +18,21 @@ from .test_etcd import etcd_read, socket_getaddrinfo
from .test_ha import get_cluster_initialized_without_leader, get_cluster_initialized_with_leader, \ from .test_ha import get_cluster_initialized_without_leader, get_cluster_initialized_with_leader, \
get_cluster_initialized_with_only_leader, get_cluster_not_initialized_without_leader, get_cluster, Member get_cluster_initialized_with_only_leader, get_cluster_not_initialized_without_leader, get_cluster, Member
CONFIG_FILE_PATH = './test-ctl.yaml'
def test_rw_config(): def test_rw_config():
runner = CliRunner() runner = CliRunner()
with runner.isolated_filesystem(): with runner.isolated_filesystem():
load_config(CONFIG_FILE_PATH + '/dummy', None) load_config(CONFIG_FILE_PATH, None)
store_config({'etcd': {'host': 'localhost:2379'}}, CONFIG_FILE_PATH + '/dummy') CONFIG_PATH = './test-ctl.yaml'
load_config(CONFIG_FILE_PATH + '/dummy', '0.0.0.0') store_config({'etcd': {'host': 'localhost:2379'}}, CONFIG_PATH + '/dummy')
os.remove(CONFIG_FILE_PATH + '/dummy') load_config(CONFIG_PATH + '/dummy', '0.0.0.0')
os.rmdir(CONFIG_FILE_PATH) os.remove(CONFIG_PATH + '/dummy')
os.rmdir(CONFIG_PATH)
@patch('patroni.ctl.load_config', @patch('patroni.ctl.load_config', Mock(return_value={
Mock(return_value={'scope': 'alpha', 'postgresql': {'data_dir': '.', 'parameters': {}, 'retry_timeout': 5}, 'scope': 'alpha', 'restapi': {'listen': '::', 'certfile': 'a'}, 'etcd': {'host': 'localhost:2379'},
'restapi': {'listen': '::', 'certfile': 'a'}, 'etcd': {'host': 'localhost:2379'}})) 'postgresql': {'data_dir': '.', 'pgpass': './pgpass', 'parameters': {}, 'retry_timeout': 5}}))
class TestCtl(unittest.TestCase): class TestCtl(unittest.TestCase):
@patch('socket.getaddrinfo', socket_getaddrinfo) @patch('socket.getaddrinfo', socket_getaddrinfo)
@@ -43,6 +42,12 @@ class TestCtl(unittest.TestCase):
self.runner = CliRunner() self.runner = CliRunner()
self.e = get_dcs({'etcd': {'ttl': 30, 'host': 'ok:2379', 'retry_timeout': 10}}, 'foo') self.e = get_dcs({'etcd': {'ttl': 30, 'host': 'ok:2379', 'retry_timeout': 10}}, 'foo')
def test_load_config(self):
runner = CliRunner()
with runner.isolated_filesystem():
self.assertRaises(PatroniCtlException, load_config, './non-existing-config-file', None)
self.assertRaises(PatroniCtlException, load_config, './non-existing-config-file', None)
@patch('psycopg2.connect', psycopg2_connect) @patch('psycopg2.connect', psycopg2_connect)
def test_get_cursor(self): def test_get_cursor(self):
self.assertIsNone(get_cursor(get_cluster_initialized_without_leader(), {}, role='master')) self.assertIsNone(get_cursor(get_cluster_initialized_without_leader(), {}, role='master'))
@@ -67,10 +72,9 @@ class TestCtl(unittest.TestCase):
def test_output_members(self): def test_output_members(self):
scheduled_at = datetime.now(tzutc) + timedelta(seconds=600) scheduled_at = datetime.now(tzutc) + timedelta(seconds=600)
cluster = get_cluster_initialized_with_leader(Failover(1, 'foo', 'bar', scheduled_at)) cluster = get_cluster_initialized_with_leader(Failover(1, 'foo', 'bar', scheduled_at))
self.assertIsNone(output_members(cluster, name='abc', fmt='pretty')) del cluster.members[1].data['conn_url']
self.assertIsNone(output_members(cluster, name='abc', fmt='json')) for fmt in ('pretty', 'json', 'yaml', 'tsv'):
self.assertIsNone(output_members(cluster, name='abc', fmt='yaml')) self.assertIsNone(output_members(cluster, name='abc', fmt=fmt))
self.assertIsNone(output_members(cluster, name='abc', fmt='tsv'))
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
@patch.object(PoolManager, 'request', Mock(return_value=MockResponse())) @patch.object(PoolManager, 'request', Mock(return_value=MockResponse()))
@@ -200,9 +204,6 @@ class TestCtl(unittest.TestCase):
rows = query_member(None, None, None, 'master', 'SELECT pg_catalog.pg_is_in_recovery()', {}) rows = query_member(None, None, None, 'master', 'SELECT pg_catalog.pg_is_in_recovery()', {})
self.assertTrue('False' in str(rows)) self.assertTrue('False' in str(rows))
rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {})
self.assertEqual(rows, (None, None))
with patch.object(MockCursor, 'execute', Mock(side_effect=OperationalError('bla'))): with patch.object(MockCursor, 'execute', Mock(side_effect=OperationalError('bla'))):
rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {}) rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {})
@@ -590,3 +591,14 @@ class TestCtl(unittest.TestCase):
mock_get_dcs.return_value.get_cluster = get_cluster_not_initialized_without_leader mock_get_dcs.return_value.get_cluster = get_cluster_not_initialized_without_leader
result = self.runner.invoke(ctl, ['reinit', 'dummy']) result = self.runner.invoke(ctl, ['reinit', 'dummy'])
assert "cluster doesn\'t have any members" in result.output assert "cluster doesn\'t have any members" in result.output
@patch('time.sleep', Mock())
@patch('patroni.ctl.get_dcs')
def test_reinit_wait(self, mock_get_dcs):
mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader
with patch.object(PoolManager, 'request') as mocked:
mocked.side_effect = [Mock(data=s, status=200) for s in
[b"reinitialize", b'{"state":"creating replica"}', b'{"state":"running"}']]
result = self.runner.invoke(ctl, ['reinit', 'alpha', 'other', '--wait'], input='y\ny')
self.assertIn("Waiting for reinitialize to complete on: other", result.output)
self.assertIn("Reinitialize is completed on: other", result.output)
+21 -14
View File
@@ -130,12 +130,11 @@ class TestClient(unittest.TestCase):
self.client.http.request_encode_body = http_request self.client.http.request_encode_body = http_request
def test_machines(self): def test_machines(self):
self.client._base_uri = 'http://localhost:4001' self.client._base_uri = 'http://localhost:4002'
self.client._machines_cache = ['http://localhost:2379'] self.client._machines_cache = ['http://localhost:4002', 'http://localhost:2379']
self.assertIsNotNone(self.client.machines) self.assertIsNotNone(self.client.machines)
self.client._base_uri = 'http://localhost:4001' self.client._base_uri = 'http://localhost:4001'
self.client._machines_cache = [] self.client._machines_cache = ['http://localhost:4001']
self.assertIsNotNone(self.client.machines)
self.client._update_machines_cache = True self.client._update_machines_cache = True
machines = None machines = None
try: try:
@@ -146,16 +145,13 @@ class TestClient(unittest.TestCase):
@patch.object(Client, 'machines') @patch.object(Client, 'machines')
def test_api_execute(self, mock_machines): def test_api_execute(self, mock_machines):
mock_machines.__get__ = Mock(return_value=['http://localhost:2379']) mock_machines.__get__ = Mock(return_value=['http://localhost:4001', 'http://localhost:2379'])
self.assertRaises(ValueError, self.client.api_execute, '', '') self.assertRaises(ValueError, self.client.api_execute, '', '')
self.client._base_uri = 'http://localhost:4001' self.client._base_uri = 'http://localhost:4001'
self.client._machines_cache = ['http://localhost:2379']
self.assertRaises(etcd.EtcdException, self.client.api_execute, '/', 'POST', timeout=0) self.assertRaises(etcd.EtcdException, self.client.api_execute, '/', 'POST', timeout=0)
self.client._base_uri = 'http://localhost:4001' self.client._base_uri = 'http://localhost:4001'
self.client._machines_cache = ['http://localhost:2379']
rtry = Retry(deadline=10, max_delay=1, max_tries=-1, retry_exceptions=(etcd.EtcdLeaderElectionInProgress,)) rtry = Retry(deadline=10, max_delay=1, max_tries=-1, retry_exceptions=(etcd.EtcdLeaderElectionInProgress,))
rtry(self.client.api_execute, '/', 'POST', timeout=0, params={'retry': rtry}) rtry(self.client.api_execute, '/', 'POST', timeout=0, params={'retry': rtry})
mock_machines.__get__ = Mock(return_value=['http://localhost:2379'])
self.client._machines_cache_updated = 0 self.client._machines_cache_updated = 0
self.client.api_execute('/', 'POST', timeout=0) self.client.api_execute('/', 'POST', timeout=0)
self.client._machines_cache = [self.client._base_uri] self.client._machines_cache = [self.client._base_uri]
@@ -163,10 +159,17 @@ class TestClient(unittest.TestCase):
self.assertRaises(etcd.EtcdWatchTimedOut, self.client.api_execute, '/timeout', 'POST', params={'wait': 'true'}) self.assertRaises(etcd.EtcdWatchTimedOut, self.client.api_execute, '/timeout', 'POST', params={'wait': 'true'})
self.assertRaises(etcd.EtcdException, self.client.api_execute, '/', '') self.assertRaises(etcd.EtcdException, self.client.api_execute, '/', '')
with patch.object(Client, '_do_http_request', Mock(side_effect=etcd.EtcdConnectionFailed)): with patch.object(Client, '_calculate_timeouts', Mock(side_effect=[(1, 1, 0), (1, 1, 0), (0, 1, 0)])),\
with patch.object(Client, '_calculate_timeouts', Mock(side_effect=[(1, 1, 0), (1, 1, 0), (0, 1, 0)])): patch.object(Client, '_load_machines_cache', Mock(side_effect=Exception)):
self.assertRaises(etcd.EtcdException, rtry, self.client.api_execute, '/', 'GET', params={'retry': rtry}) self.client.http.request = Mock(side_effect=socket.error)
self.client._read_timeout = 0 self.assertRaises(etcd.EtcdException, rtry, self.client.api_execute, '/', 'GET', params={'retry': rtry})
with patch.object(Client, '_calculate_timeouts', Mock(side_effect=[(1, 1, 0), (1, 1, 0), (0, 1, 0)])),\
patch.object(Client, '_load_machines_cache', Mock(return_value=True)):
self.assertRaises(etcd.EtcdException, rtry, self.client.api_execute, '/', 'GET', params={'retry': rtry})
with patch.object(Client, '_do_http_request', Mock(side_effect=etcd.EtcdException)):
self.client._read_timeout = 0.01
self.assertRaises(etcd.EtcdException, self.client.api_execute, '/', 'GET') self.assertRaises(etcd.EtcdException, self.client.api_execute, '/', 'GET')
def test_get_srv_record(self): def test_get_srv_record(self):
@@ -182,8 +185,12 @@ class TestClient(unittest.TestCase):
self.client._get_machines_cache_from_dns('error', 2379) self.client._get_machines_cache_from_dns('error', 2379)
@patch.object(Client, 'machines') @patch.object(Client, 'machines')
def test__load_machines_cache(self, mock_machines): def test__refresh_machines_cache(self, mock_machines):
mock_machines.__get__ = Mock(return_value=['http://localhost:2379']) mock_machines.__get__ = Mock(side_effect=etcd.EtcdConnectionFailed)
self.assertIsNone(self.client._refresh_machines_cache())
self.assertRaises(etcd.EtcdException, self.client._refresh_machines_cache, True)
def test__load_machines_cache(self):
self.client._config = {} self.client._config = {}
self.assertRaises(Exception, self.client._load_machines_cache) self.assertRaises(Exception, self.client._load_machines_cache)
self.client._config = {'srv': 'blabla'} self.client._config = {'srv': 'blabla'}
+23 -3
View File
@@ -150,7 +150,7 @@ def run_async(self, func, args=()):
@patch.object(Postgresql, 'is_running', Mock(return_value=MockPostmaster())) @patch.object(Postgresql, 'is_running', Mock(return_value=MockPostmaster()))
@patch.object(Postgresql, 'is_leader', Mock(return_value=True)) @patch.object(Postgresql, 'is_leader', Mock(return_value=True))
@patch.object(Postgresql, 'timeline_wal_position', Mock(return_value=(1, 10))) @patch.object(Postgresql, 'timeline_wal_position', Mock(return_value=(1, 10, 1)))
@patch.object(Postgresql, '_cluster_info_state_get', Mock(return_value=3)) @patch.object(Postgresql, '_cluster_info_state_get', Mock(return_value=3))
@patch.object(Postgresql, 'call_nowait', Mock(return_value=True)) @patch.object(Postgresql, 'call_nowait', Mock(return_value=True))
@patch.object(Postgresql, 'data_directory_empty', Mock(return_value=False)) @patch.object(Postgresql, 'data_directory_empty', Mock(return_value=False))
@@ -172,6 +172,7 @@ def run_async(self, func, args=()):
@patch('patroni.postgresql.polling_loop', Mock(return_value=range(1))) @patch('patroni.postgresql.polling_loop', Mock(return_value=range(1)))
@patch('patroni.async_executor.AsyncExecutor.busy', PropertyMock(return_value=False)) @patch('patroni.async_executor.AsyncExecutor.busy', PropertyMock(return_value=False))
@patch('patroni.async_executor.AsyncExecutor.run_async', run_async) @patch('patroni.async_executor.AsyncExecutor.run_async', run_async)
@patch('patroni.postgresql.rewind.Thread', Mock())
@patch('subprocess.call', Mock(return_value=0)) @patch('subprocess.call', Mock(return_value=0))
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
class TestHa(PostgresInit): class TestHa(PostgresInit):
@@ -199,9 +200,12 @@ class TestHa(PostgresInit):
self.assertTrue(self.ha.update_lock(True)) self.assertTrue(self.ha.update_lock(True))
def test_touch_member(self): def test_touch_member(self):
self.p.timeline_wal_position = Mock(return_value=(0, 1)) self.p.timeline_wal_position = Mock(return_value=(0, 1, 0))
self.p.replica_cached_timeline = Mock(side_effect=Exception) self.p.replica_cached_timeline = Mock(side_effect=Exception)
self.ha.touch_member() self.ha.touch_member()
self.p.timeline_wal_position = Mock(return_value=(0, 1, 1))
self.p.set_role('standby_leader')
self.ha.touch_member()
def test_is_leader(self): def test_is_leader(self):
self.assertFalse(self.ha.is_leader()) self.assertFalse(self.ha.is_leader())
@@ -601,7 +605,7 @@ class TestHa(PostgresInit):
# in synchronous_mode consider itself healthy if the former leader is accessible in read-only and ahead of us # in synchronous_mode consider itself healthy if the former leader is accessible in read-only and ahead of us
with patch.object(Ha, 'is_synchronous_mode', Mock(return_value=True)): with patch.object(Ha, 'is_synchronous_mode', Mock(return_value=True)):
self.assertTrue(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertTrue(self.ha._is_healthiest_node(self.ha.old_cluster.members))
with patch('patroni.postgresql.Postgresql.timeline_wal_position', return_value=(1, 1)): with patch('patroni.postgresql.Postgresql.timeline_wal_position', return_value=(1, 1, 1)):
self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members))
with patch('patroni.postgresql.Postgresql.replica_cached_timeline', return_value=1): with patch('patroni.postgresql.Postgresql.replica_cached_timeline', return_value=1):
self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members))
@@ -615,12 +619,17 @@ class TestHa(PostgresInit):
member = Member(0, 'test', 1, {'api_url': 'http://localhost:8011/patroni'}) member = Member(0, 'test', 1, {'api_url': 'http://localhost:8011/patroni'})
self.ha.fetch_node_status(member) self.ha.fetch_node_status(member)
@patch.object(Rewind, 'pg_rewind', true)
@patch.object(Rewind, 'check_leader_is_not_in_recovery', true)
def test_post_recover(self): def test_post_recover(self):
self.p.is_running = false self.p.is_running = false
self.ha.has_lock = true self.ha.has_lock = true
self.p.set_role('master')
self.assertEqual(self.ha.post_recover(), 'removed leader key after trying and failing to start postgres') self.assertEqual(self.ha.post_recover(), 'removed leader key after trying and failing to start postgres')
self.ha.has_lock = false self.ha.has_lock = false
self.assertEqual(self.ha.post_recover(), 'failed to start postgres') self.assertEqual(self.ha.post_recover(), 'failed to start postgres')
leader = Leader(0, 0, Member(0, 'l', 2, {"version": "1.6", "conn_url": "postgres://a", "role": "master"}))
self.ha._rewind.execute(leader)
self.p.is_running = true self.p.is_running = true
self.assertIsNone(self.ha.post_recover()) self.assertIsNone(self.ha.post_recover())
@@ -809,6 +818,17 @@ class TestHa(PostgresInit):
self.assertEqual(self.ha.run_cycle(), 'stopped PostgreSQL to fail over after a crash') self.assertEqual(self.ha.run_cycle(), 'stopped PostgreSQL to fail over after a crash')
demote.assert_called_once() demote.assert_called_once()
def test_master_stop_timeout(self):
self.assertEqual(self.ha.master_stop_timeout(), None)
self.ha.patroni.config.set_dynamic_configuration({'master_stop_timeout': 30})
with patch.object(Ha, 'is_synchronous_mode', Mock(return_value=True)):
self.assertEqual(self.ha.master_stop_timeout(), 30)
self.ha.patroni.config.set_dynamic_configuration({'master_stop_timeout': 30})
with patch.object(Ha, 'is_synchronous_mode', Mock(return_value=False)):
self.assertEqual(self.ha.master_stop_timeout(), None)
self.ha.patroni.config.set_dynamic_configuration({'master_stop_timeout': None})
self.assertEqual(self.ha.master_stop_timeout(), None)
@patch('patroni.postgresql.Postgresql.follow') @patch('patroni.postgresql.Postgresql.follow')
def test_demote_immediate(self, follow): def test_demote_immediate(self, follow):
self.ha.has_lock = true self.ha.has_lock = true
+22 -6
View File
@@ -34,19 +34,26 @@ def mock_config_map(*args, **kwargs):
return mock return mock
@patch('socket.TCP_KEEPIDLE', 4, create=True)
@patch('socket.TCP_KEEPINTVL', 5, create=True)
@patch('socket.TCP_KEEPCNT', 6, create=True)
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map', mock_config_map) @patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map', mock_config_map)
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_config_map', mock_config_map) @patch.object(k8s_client.CoreV1Api, 'create_namespaced_config_map', mock_config_map)
@patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True) @patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True)
@patch.object(Thread, 'start', Mock()) @patch.object(Thread, 'start', Mock())
class TestKubernetes(unittest.TestCase): class TestKubernetes(unittest.TestCase):
@patch('socket.TCP_KEEPIDLE', 4, create=True)
@patch('socket.TCP_KEEPINTVL', 5, create=True)
@patch('socket.TCP_KEEPCNT', 6, create=True)
@patch('kubernetes.config.load_kube_config', Mock()) @patch('kubernetes.config.load_kube_config', Mock())
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map) @patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map)
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', mock_list_namespaced_pod) @patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', mock_list_namespaced_pod)
@patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True) @patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True)
@patch.object(Thread, 'start', Mock()) @patch.object(Thread, 'start', Mock())
def setUp(self): def setUp(self):
self.k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10, 'labels': {'f': 'b'}}) self.k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0',
'loop_wait': 10, 'retry_timeout': 10, 'labels': {'f': 'b'}})
self.assertRaises(AttributeError, self.k._pods._build_cache) self.assertRaises(AttributeError, self.k._pods._build_cache)
self.k._pods._is_ready = True self.k._pods._is_ready = True
self.assertRaises(AttributeError, self.k._kinds._build_cache) self.assertRaises(AttributeError, self.k._kinds._build_cache)
@@ -71,14 +78,14 @@ class TestKubernetes(unittest.TestCase):
@patch('kubernetes.config.load_kube_config', Mock()) @patch('kubernetes.config.load_kube_config', Mock())
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock()) @patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock())
def test_update_leader(self): def test_update_leader(self):
k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10, k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'loop_wait': 10, 'retry_timeout': 10,
'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'}) 'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'})
self.assertIsNotNone(k.update_leader('123')) self.assertIsNotNone(k.update_leader('123'))
@patch('kubernetes.config.load_kube_config', Mock()) @patch('kubernetes.config.load_kube_config', Mock())
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock()) @patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock())
def test_update_leader_with_restricted_access(self): def test_update_leader_with_restricted_access(self):
k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10, k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'loop_wait': 10, 'retry_timeout': 10,
'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'}) 'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'})
self.assertIsNotNone(k.update_leader('123', True)) self.assertIsNotNone(k.update_leader('123', True))
@@ -120,7 +127,7 @@ class TestKubernetes(unittest.TestCase):
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', @patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints',
Mock(side_effect=[k8s_client.rest.ApiException(502, ''), k8s_client.rest.ApiException(500, '')])) Mock(side_effect=[k8s_client.rest.ApiException(502, ''), k8s_client.rest.ApiException(500, '')]))
def test_delete_sync_state(self): def test_delete_sync_state(self):
k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10, k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'loop_wait': 10, 'retry_timeout': 10,
'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'}) 'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'})
self.assertFalse(k.delete_sync_state()) self.assertFalse(k.delete_sync_state())
@@ -139,7 +146,7 @@ class TestKubernetes(unittest.TestCase):
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_service', @patch.object(k8s_client.CoreV1Api, 'create_namespaced_service',
Mock(side_effect=[True, False, k8s_client.rest.ApiException(500, '')])) Mock(side_effect=[True, False, k8s_client.rest.ApiException(500, '')]))
def test__create_config_service(self): def test__create_config_service(self):
k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10, k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'loop_wait': 10, 'retry_timeout': 10,
'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'}) 'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'})
self.assertIsNotNone(k.patch_or_create_config({'foo': 'bar'})) self.assertIsNotNone(k.patch_or_create_config({'foo': 'bar'}))
self.assertIsNotNone(k.patch_or_create_config({'foo': 'bar'})) self.assertIsNotNone(k.patch_or_create_config({'foo': 'bar'}))
@@ -148,11 +155,15 @@ class TestKubernetes(unittest.TestCase):
class TestCacheBuilder(unittest.TestCase): class TestCacheBuilder(unittest.TestCase):
@patch('socket.TCP_KEEPIDLE', 4, create=True)
@patch('socket.TCP_KEEPINTVL', 5, create=True)
@patch('socket.TCP_KEEPCNT', 6, create=True)
@patch('kubernetes.config.load_kube_config', Mock()) @patch('kubernetes.config.load_kube_config', Mock())
@patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True) @patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True)
@patch.object(Thread, 'start', Mock()) @patch.object(Thread, 'start', Mock())
def setUp(self): def setUp(self):
self.k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10, 'labels': {'f': 'b'}}) self.k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0',
'loop_wait': 10, 'retry_timeout': 10, 'labels': {'f': 'b'}})
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map) @patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map)
@patch('patroni.dcs.kubernetes.ObjectCache._watch') @patch('patroni.dcs.kubernetes.ObjectCache._watch')
@@ -172,3 +183,8 @@ class TestCacheBuilder(unittest.TestCase):
@patch('patroni.dcs.kubernetes.ObjectCache._build_cache', Mock(side_effect=Exception)) @patch('patroni.dcs.kubernetes.ObjectCache._build_cache', Mock(side_effect=Exception))
def test_run(self): def test_run(self):
self.assertRaises(SleepException, self.k._pods.run) self.assertRaises(SleepException, self.k._pods.run)
@patch('time.sleep', Mock())
def test__list(self):
self.k._pods._func = Mock(side_effect=Exception)
self.assertRaises(Exception, self.k._pods._list)
+6 -1
View File
@@ -44,7 +44,11 @@ class TestPatroni(unittest.TestCase):
def test_no_config(self): def test_no_config(self):
self.assertRaises(SystemExit, patroni_main) self.assertRaises(SystemExit, patroni_main)
@patch('pkgutil.get_importer', Mock(return_value=MockFrozenImporter())) @patch('sys.argv', ['patroni.py', '--validate-config', 'postgres0.yml'])
def test_validate_config(self):
self.assertRaises(SystemExit, patroni_main)
@patch('pkgutil.iter_importers', Mock(return_value=[MockFrozenImporter()]))
@patch('sys.frozen', Mock(return_value=True), create=True) @patch('sys.frozen', Mock(return_value=True), create=True)
@patch.object(BaseHTTPServer.HTTPServer, '__init__', Mock()) @patch.object(BaseHTTPServer.HTTPServer, '__init__', Mock())
@patch.object(etcd.Client, 'read', etcd_read) @patch.object(etcd.Client, 'read', etcd_read)
@@ -174,6 +178,7 @@ class TestPatroni(unittest.TestCase):
@patch.object(Thread, 'join', Mock()) @patch.object(Thread, 'join', Mock())
def test_shutdown(self): def test_shutdown(self):
self.p.api.shutdown = Mock(side_effect=Exception) self.p.api.shutdown = Mock(side_effect=Exception)
self.p.ha.shutdown = Mock(side_effect=Exception)
self.p.shutdown() self.p.shutdown()
def test_check_psycopg2(self): def test_check_psycopg2(self):
+40 -9
View File
@@ -1,5 +1,6 @@
import mock # for the mock.call method, importing it without a namespace breaks python3 import mock # for the mock.call method, importing it without a namespace breaks python3
import os import os
import psutil
import psycopg2 import psycopg2
import re import re
import subprocess import subprocess
@@ -8,7 +9,7 @@ import time
from mock import Mock, MagicMock, PropertyMock, patch, mock_open from mock import Mock, MagicMock, PropertyMock, patch, mock_open
from patroni.async_executor import CriticalTask from patroni.async_executor import CriticalTask
from patroni.dcs import Cluster, ClusterConfig, Member, RemoteMember, SyncState from patroni.dcs import Cluster, ClusterConfig, Member, RemoteMember, SyncState
from patroni.exceptions import PostgresConnectionException from patroni.exceptions import PostgresConnectionException, PatroniException
from patroni.postgresql import Postgresql, STATE_REJECT, STATE_NO_RESPONSE from patroni.postgresql import Postgresql, STATE_REJECT, STATE_NO_RESPONSE
from patroni.postgresql.postmaster import PostmasterProcess from patroni.postgresql.postmaster import PostmasterProcess
from patroni.postgresql.slots import SlotsHandler from patroni.postgresql.slots import SlotsHandler
@@ -134,6 +135,9 @@ class TestPostgresql(BaseTestPostgresql):
self.p.cancellable.cancel() self.p.cancellable.cancel()
self.assertFalse(self.p.start()) self.assertFalse(self.p.start())
with patch('patroni.postgresql.config.ConfigHandler.effective_configuration',
PropertyMock(side_effect=Exception)):
self.assertIsNone(self.p.start())
@patch.object(Postgresql, 'pg_isready') @patch.object(Postgresql, 'pg_isready')
@patch('patroni.postgresql.polling_loop', Mock(return_value=range(1))) @patch('patroni.postgresql.polling_loop', Mock(return_value=range(1)))
@@ -174,6 +178,17 @@ class TestPostgresql(BaseTestPostgresql):
mock_callback.assert_called() mock_callback.assert_called()
mock_postmaster.signal_stop.assert_called() mock_postmaster.signal_stop.assert_called()
# Timed out waiting for fast shutdown triggers immediate shutdown
mock_postmaster.wait.side_effect = [psutil.TimeoutExpired(30), psutil.TimeoutExpired(30), Mock()]
mock_callback.reset_mock()
self.assertTrue(self.p.stop(on_safepoint=mock_callback, stop_timeout=30))
mock_callback.assert_called()
mock_postmaster.signal_stop.assert_called()
# Immediate shutdown succeeded
mock_postmaster.wait.side_effect = [psutil.TimeoutExpired(30), Mock()]
self.assertTrue(self.p.stop(on_safepoint=mock_callback, stop_timeout=30))
# Stop signal failed # Stop signal failed
mock_postmaster.signal_stop.return_value = False mock_postmaster.signal_stop.return_value = False
self.assertFalse(self.p.stop()) self.assertFalse(self.p.stop())
@@ -184,6 +199,11 @@ class TestPostgresql(BaseTestPostgresql):
self.assertTrue(self.p.stop(on_safepoint=mock_callback)) self.assertTrue(self.p.stop(on_safepoint=mock_callback))
mock_callback.assert_called() mock_callback.assert_called()
# Fast shutdown is timed out but when immediate postmaster is already gone
mock_postmaster.wait.side_effect = [psutil.TimeoutExpired(30), Mock()]
mock_postmaster.signal_stop.side_effect = [None, True]
self.assertTrue(self.p.stop(on_safepoint=mock_callback, stop_timeout=30))
def test_restart(self): def test_restart(self):
self.p.start = Mock(return_value=False) self.p.start = Mock(return_value=False)
self.assertFalse(self.p.restart()) self.assertFalse(self.p.restart())
@@ -200,20 +220,22 @@ class TestPostgresql(BaseTestPostgresql):
self.assertEqual(self.p.checkpoint({'user': 'postgres'}), 'is_in_recovery=true') self.assertEqual(self.p.checkpoint({'user': 'postgres'}), 'is_in_recovery=true')
with patch.object(MockCursor, 'execute', Mock(return_value=None)): with patch.object(MockCursor, 'execute', Mock(return_value=None)):
self.assertIsNone(self.p.checkpoint()) self.assertIsNone(self.p.checkpoint())
self.assertEqual(self.p.checkpoint(), 'not accessible or not healty') self.assertEqual(self.p.checkpoint(timeout=10), 'not accessible or not healty')
@patch('patroni.postgresql.config.mtime', mock_mtime) @patch('patroni.postgresql.config.mtime', mock_mtime)
@patch('patroni.postgresql.config.ConfigHandler._get_pg_settings') @patch('patroni.postgresql.config.ConfigHandler._get_pg_settings')
def test_check_recovery_conf(self, mock_get_pg_settings): def test_check_recovery_conf(self, mock_get_pg_settings):
mock_get_pg_settings.return_value = { mock_get_pg_settings.return_value = {
'primary_conninfo': ['primary_conninfo', 'foo=', None, 'string', 'postmaster'], 'primary_conninfo': ['primary_conninfo', 'foo=', None, 'string', 'postmaster', self.p.config._auto_conf],
'recovery_min_apply_delay': ['recovery_min_apply_delay', '0', 'ms', 'integer', 'sighup'] 'recovery_min_apply_delay': ['recovery_min_apply_delay', '0', 'ms', 'integer', 'sighup', 'foo']
} }
self.assertEqual(self.p.config.check_recovery_conf(None), (True, True)) self.assertEqual(self.p.config.check_recovery_conf(None), (True, True))
self.p.config.write_recovery_conf({'standby_mode': 'on'}) self.p.config.write_recovery_conf({'standby_mode': 'on'})
self.assertEqual(self.p.config.check_recovery_conf(None), (True, True)) self.assertEqual(self.p.config.check_recovery_conf(None), (True, True))
mock_get_pg_settings.return_value['primary_conninfo'][1] = '' mock_get_pg_settings.return_value['primary_conninfo'][1] = ''
mock_get_pg_settings.return_value['recovery_min_apply_delay'][1] = '1' mock_get_pg_settings.return_value['recovery_min_apply_delay'][1] = '1'
self.assertEqual(self.p.config.check_recovery_conf(None), (False, False))
mock_get_pg_settings.return_value['recovery_min_apply_delay'][5] = self.p.config._auto_conf
self.assertEqual(self.p.config.check_recovery_conf(None), (True, False)) self.assertEqual(self.p.config.check_recovery_conf(None), (True, False))
mock_get_pg_settings.return_value['recovery_min_apply_delay'][1] = '0' mock_get_pg_settings.return_value['recovery_min_apply_delay'][1] = '0'
self.assertEqual(self.p.config.check_recovery_conf(None), (False, False)) self.assertEqual(self.p.config.check_recovery_conf(None), (False, False))
@@ -234,7 +256,8 @@ class TestPostgresql(BaseTestPostgresql):
@patch.object(MockPostmaster, 'create_time', Mock(return_value=1234567), create=True) @patch.object(MockPostmaster, 'create_time', Mock(return_value=1234567), create=True)
@patch('patroni.postgresql.config.ConfigHandler._get_pg_settings') @patch('patroni.postgresql.config.ConfigHandler._get_pg_settings')
def test__read_recovery_params(self, mock_get_pg_settings): def test__read_recovery_params(self, mock_get_pg_settings):
mock_get_pg_settings.return_value = {'primary_conninfo': ['primary_conninfo', '', None, 'string', 'postmaster']} mock_get_pg_settings.return_value = {'primary_conninfo': ['primary_conninfo', '', None, 'string',
'postmaster', self.p.config._postgresql_conf]}
self.p.config.write_recovery_conf({'standby_mode': 'on', 'primary_conninfo': {'password': 'foo'}}) self.p.config.write_recovery_conf({'standby_mode': 'on', 'primary_conninfo': {'password': 'foo'}})
self.p.config.write_postgresql_conf() self.p.config.write_postgresql_conf()
self.assertEqual(self.p.config.check_recovery_conf(None), (False, False)) self.assertEqual(self.p.config.check_recovery_conf(None), (False, False))
@@ -278,8 +301,8 @@ class TestPostgresql(BaseTestPostgresql):
@patch.object(Postgresql, 'is_running', Mock(return_value=True)) @patch.object(Postgresql, 'is_running', Mock(return_value=True))
def test_sync_replication_slots(self): def test_sync_replication_slots(self):
self.p.start() self.p.start()
config = ClusterConfig(1, {'slots': {'ls': {'database': 'a', 'plugin': 'b'}, config = ClusterConfig(1, {'slots': {'test_3': {'database': 'a', 'plugin': 'b'},
'A': 0, 'test_3': 0, 'b': {'type': 'logical', 'plugin': '1'}}}, 1) 'A': 0, 'ls': 0, 'b': {'type': 'logical', 'plugin': '1'}}}, 1)
cluster = Cluster(True, config, self.leader, 0, [self.me, self.other, self.leadermem], None, None, None) cluster = Cluster(True, config, self.leader, 0, [self.me, self.other, self.leadermem], None, None, None)
with mock.patch('patroni.postgresql.Postgresql._query', Mock(side_effect=psycopg2.OperationalError)): with mock.patch('patroni.postgresql.Postgresql._query', Mock(side_effect=psycopg2.OperationalError)):
self.p.slots_handler.sync_replication_slots(cluster) self.p.slots_handler.sync_replication_slots(cluster)
@@ -331,7 +354,7 @@ class TestPostgresql(BaseTestPostgresql):
self.assertTrue(self.p.promote(0)) self.assertTrue(self.p.promote(0))
def test_timeline_wal_position(self): def test_timeline_wal_position(self):
self.assertEqual(self.p.timeline_wal_position(), (1, 2)) self.assertEqual(self.p.timeline_wal_position(), (1, 2, 1))
Thread(target=self.p.timeline_wal_position).start() Thread(target=self.p.timeline_wal_position).start()
@patch.object(PostmasterProcess, 'from_pidfile') @patch.object(PostmasterProcess, 'from_pidfile')
@@ -389,6 +412,10 @@ class TestPostgresql(BaseTestPostgresql):
pass pass
os.makedirs(os.path.join(self.p.data_dir, 'foo')) os.makedirs(os.path.join(self.p.data_dir, 'foo'))
_symlink('foo', os.path.join(self.p.data_dir, 'pg_wal')) _symlink('foo', os.path.join(self.p.data_dir, 'pg_wal'))
os.makedirs(os.path.join(self.p.data_dir, 'foo_tsp'))
pg_tblspc = os.path.join(self.p.data_dir, 'pg_tblspc')
os.makedirs(pg_tblspc)
_symlink('../foo_tsp', os.path.join(pg_tblspc, '12345'))
self.p.remove_data_directory() self.p.remove_data_directory()
open(self.p.data_dir, 'w').close() open(self.p.data_dir, 'w').close()
self.p.remove_data_directory() self.p.remove_data_directory()
@@ -689,9 +716,13 @@ class TestPostgresql(BaseTestPostgresql):
with patch.object(Postgresql, 'controldata', with patch.object(Postgresql, 'controldata',
Mock(return_value={'max_connections setting': '200', Mock(return_value={'max_connections setting': '200',
'max_worker_processes setting': '20', 'max_worker_processes setting': '20',
'max_prepared_xacts setting': '100',
'max_locks_per_xact setting': '100', 'max_locks_per_xact setting': '100',
'max_wal_senders setting': 10})): 'max_wal_senders setting': 10})):
self.p.cancellable.cancel() self.p.cancellable.cancel()
self.assertFalse(self.p.start()) self.assertFalse(self.p.start())
self.assertTrue(self.p.pending_restart) self.assertTrue(self.p.pending_restart)
@patch('os.path.exists', Mock(return_value=True))
@patch('os.path.isfile', Mock(return_value=False))
def test_pgpass_is_dir(self):
self.assertRaises(PatroniException, self.setUp)
+48
View File
@@ -63,9 +63,42 @@ class TestPostmasterProcess(unittest.TestCase):
mock_init.side_effect = None mock_init.side_effect = None
self.assertNotEqual(PostmasterProcess.from_pid(123), None) self.assertNotEqual(PostmasterProcess.from_pid(123), None)
@patch('psutil.Process.__init__', Mock())
@patch('psutil.wait_procs', Mock())
@patch('psutil.Process.suspend')
@patch('psutil.Process.children')
@patch('psutil.Process.kill')
def test_signal_kill(self, mock_kill, mock_children, mock_suspend):
proc = PostmasterProcess(123)
# all processes successfully stopped
mock_children.return_value = [Mock()]
mock_children.return_value[0].kill.side_effect = psutil.Error
self.assertTrue(proc.signal_kill())
# postmaster has gone before suspend
mock_suspend.side_effect = psutil.NoSuchProcess(123)
self.assertTrue(proc.signal_kill())
# postmaster has gone before we got a list of children
mock_suspend.side_effect = psutil.Error()
mock_children.side_effect = psutil.NoSuchProcess(123)
self.assertTrue(proc.signal_kill())
# postmaster has gone after we got a list of children
mock_children.side_effect = psutil.Error()
mock_kill.side_effect = psutil.NoSuchProcess(123)
self.assertTrue(proc.signal_kill())
# failed to kill postmaster
mock_kill.side_effect = psutil.AccessDenied(123)
self.assertFalse(proc.signal_kill())
@patch('psutil.Process.__init__', Mock()) @patch('psutil.Process.__init__', Mock())
@patch('psutil.Process.send_signal') @patch('psutil.Process.send_signal')
@patch('psutil.Process.pid', Mock(return_value=123)) @patch('psutil.Process.pid', Mock(return_value=123))
@patch('os.name', 'posix')
@patch('signal.SIGQUIT', 3, create=True)
def test_signal_stop(self, mock_send_signal): def test_signal_stop(self, mock_send_signal):
proc = PostmasterProcess(-123) proc = PostmasterProcess(-123)
self.assertEqual(proc.signal_stop('immediate'), False) self.assertEqual(proc.signal_stop('immediate'), False)
@@ -76,6 +109,21 @@ class TestPostmasterProcess(unittest.TestCase):
self.assertEqual(proc.signal_stop('immediate'), True) self.assertEqual(proc.signal_stop('immediate'), True)
self.assertEqual(proc.signal_stop('immediate'), False) self.assertEqual(proc.signal_stop('immediate'), False)
@patch('psutil.Process.__init__', Mock())
@patch('patroni.postgresql.postmaster.os')
@patch('subprocess.call', Mock(side_effect=[0, OSError, 1]))
@patch('psutil.Process.pid', Mock(return_value=123))
@patch('psutil.Process.is_running', Mock(return_value=False))
def test_signal_stop_nt(self, mock_os):
mock_os.configure_mock(name="nt")
proc = PostmasterProcess(-123)
self.assertEqual(proc.signal_stop('immediate'), False)
proc = PostmasterProcess(123)
self.assertEqual(proc.signal_stop('immediate'), None)
self.assertEqual(proc.signal_stop('immediate'), False)
self.assertEqual(proc.signal_stop('immediate'), True)
@patch('psutil.Process.__init__', Mock()) @patch('psutil.Process.__init__', Mock())
@patch('psutil.wait_procs') @patch('psutil.wait_procs')
def test_wait_for_user_backends_to_close(self, mock_wait): def test_wait_for_user_backends_to_close(self, mock_wait):
+28 -3
View File
@@ -7,6 +7,16 @@ from patroni.postgresql.rewind import Rewind
from . import BaseTestPostgresql, MockCursor, psycopg2_connect from . import BaseTestPostgresql, MockCursor, psycopg2_connect
class MockThread(object):
def __init__(self, target, args):
self._target = target
self._args = args
def start(self):
self._target(*self._args)
@patch('subprocess.call', Mock(return_value=0)) @patch('subprocess.call', Mock(return_value=0))
@patch('psycopg2.connect', psycopg2_connect) @patch('psycopg2.connect', psycopg2_connect)
class TestRewind(BaseTestPostgresql): class TestRewind(BaseTestPostgresql):
@@ -102,6 +112,21 @@ class TestRewind(BaseTestPostgresql):
self.r.check_leader_is_not_in_recovery() self.r.check_leader_is_not_in_recovery()
self.r.check_leader_is_not_in_recovery() self.r.check_leader_is_not_in_recovery()
@patch.object(Postgresql, 'controldata', Mock(return_value={"Latest checkpoint's TimeLineID": 1})) @patch('patroni.postgresql.rewind.Thread', MockThread)
def test_check_for_checkpoint_after_promote(self): @patch.object(Postgresql, 'controldata')
self.r.check_for_checkpoint_after_promote() @patch.object(Postgresql, 'checkpoint')
def test_ensure_checkpoint_after_promote(self, mock_checkpoint, mock_controldata):
mock_checkpoint.return_value = None
self.r.ensure_checkpoint_after_promote()
self.r.ensure_checkpoint_after_promote()
self.r.reset_state()
mock_controldata.return_value = {"Latest checkpoint's TimeLineID": 1}
mock_checkpoint.side_effect = Exception
self.r.ensure_checkpoint_after_promote()
self.r.ensure_checkpoint_after_promote()
self.r.reset_state()
mock_controldata.side_effect = TypeError
self.r.ensure_checkpoint_after_promote()
self.r.ensure_checkpoint_after_promote()
+24 -1
View File
@@ -2,7 +2,7 @@ import unittest
from mock import Mock, patch from mock import Mock, patch
from patroni.exceptions import PatroniException from patroni.exceptions import PatroniException
from patroni.utils import Retry, RetryFailedError, polling_loop from patroni.utils import Retry, RetryFailedError, polling_loop, validate_directory
class TestUtils(unittest.TestCase): class TestUtils(unittest.TestCase):
@@ -10,6 +10,29 @@ class TestUtils(unittest.TestCase):
def test_polling_loop(self): def test_polling_loop(self):
self.assertEqual(list(polling_loop(0.001, interval=0.001)), [0]) self.assertEqual(list(polling_loop(0.001, interval=0.001)), [0])
@patch('os.path.exists', Mock(return_value=True))
@patch('os.path.isdir', Mock(return_value=True))
@patch('tempfile.mkstemp', Mock(return_value=("", "")))
@patch('os.remove', Mock(side_effect=Exception))
def test_validate_directory_writable(self):
self.assertRaises(Exception, validate_directory, "/tmp")
@patch('os.path.exists', Mock(return_value=True))
@patch('os.path.isdir', Mock(return_value=True))
@patch('tempfile.mkstemp', Mock(side_effect=OSError))
def test_validate_directory_not_writable(self):
self.assertRaises(PatroniException, validate_directory, "/tmp")
@patch('os.path.exists', Mock(return_value=False))
@patch('os.makedirs', Mock(side_effect=OSError))
def test_validate_directory_couldnt_create(self):
self.assertRaises(PatroniException, validate_directory, "/tmp")
@patch('os.path.exists', Mock(return_value=True))
@patch('os.path.isdir', Mock(return_value=False))
def test_validate_directory_is_not_a_directory(self):
self.assertRaises(PatroniException, validate_directory, "/tmp")
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
class TestRetrySleeper(unittest.TestCase): class TestRetrySleeper(unittest.TestCase):
+229
View File
@@ -0,0 +1,229 @@
import copy
import os
import socket
import tempfile
import unittest
from mock import Mock, patch, mock_open
from patroni.dcs import dcs_modules
from patroni.validator import schema
from six import StringIO
available_dcs = [m.split(".")[-1] for m in dcs_modules()]
config = {
"name": "string",
"scope": "string",
"restapi": {
"listen": "127.0.0.2:800",
"connect_address": "127.0.0.2:800"
},
"bootstrap": {
"dcs": {
"ttl": 1000,
"loop_wait": 1000,
"retry_timeout": 1000,
"maximum_lag_on_failover": 1000
},
"pg_hba": ["string"],
"initdb": ["string", {"key": "value"}]
},
"consul": {
"host": "127.0.0.1:5000"
},
"etcd": {
"hosts": "127.0.0.1:2379,127.0.0.1:2380"
},
"exhibitor": {
"hosts": ["string"],
"port": 4000,
"pool_interval": 1000
},
"zookeeper": {
"hosts": "127.0.0.1:3379,127.0.0.1:3380"
},
"kubernetes": {
"namespace": "string",
"labels": {},
"scope_label": "string",
"role_label": "string",
"use_endpoints": False,
"pod_ip": "127.0.0.1",
"ports": [{"name": "string", "port": 1000}],
},
"postgresql": {
"listen": "127.0.0.2,::1:543",
"connect_address": "127.0.0.2:543",
"authentication": {
"replication": {"username": "user"},
"superuser": {"username": "user"},
"rewind": {"username": "user"},
},
"data_dir": os.path.join(tempfile.gettempdir(), "data_dir"),
"bin_dir": os.path.join(tempfile.gettempdir(), "bin_dir"),
"parameters": {
"unix_socket_directories": "."
},
"pg_hba": [u"string"],
"pg_ident": ["string"],
"pg_ctl_timeout": 1000,
"use_pg_rewind": False
},
"watchdog": {
"mode": "off",
"device": "string"
},
"tags": {
"nofailover": False,
"clonefrom": False,
"noloadbalance": False,
"nosync": False
}
}
directories = []
files = []
def isfile_side_effect(arg):
if arg.endswith('.exe'):
arg = arg[:-4]
return arg in files
def isdir_side_effect(arg):
return arg in directories
def exists_side_effect(arg):
return isfile_side_effect(arg) or isdir_side_effect(arg)
def connect_side_effect(host_port):
_, port = host_port
if port < 1000:
return 1
elif port < 10000:
return 0
else:
raise socket.gaierror()
def parse_output(output):
result = []
for s in output.split("\n"):
x = s.split(" ")[0]
if x and x not in result:
result.append(x)
result.sort()
return result
@patch('socket.socket.connect_ex', Mock(side_effect=connect_side_effect))
@patch('os.path.exists', Mock(side_effect=exists_side_effect))
@patch('os.path.isdir', Mock(side_effect=isdir_side_effect))
@patch('os.path.isfile', Mock(side_effect=isfile_side_effect))
@patch('sys.stderr', new_callable=StringIO)
@patch('sys.stdout', new_callable=StringIO)
class TestValidator(unittest.TestCase):
def setUp(self):
del files[:]
del directories[:]
def test_empty_config(self, mock_out, mock_err):
schema({})
output = mock_out.getvalue()
expected = list(sorted(['name', 'postgresql', 'restapi', 'scope'] + available_dcs))
self.assertEqual(expected, parse_output(output))
def test_complete_config(self, mock_out, mock_err):
schema(config)
output = mock_out.getvalue()
self.assertEqual(['postgresql.bin_dir'], parse_output(output))
def test_bin_dir_is_file(self, mock_out, mock_err):
files.append(config["postgresql"]["data_dir"])
files.append(config["postgresql"]["bin_dir"])
c = copy.deepcopy(config)
c["restapi"]["connect_address"] = 'False:blabla'
c["etcd"]["hosts"] = ["127.0.0.1:2379", "1244.0.0.1:2379", "127.0.0.1:invalidport"]
c["kubernetes"]["pod_ip"] = "127.0.0.1111"
schema(c)
output = mock_out.getvalue()
self.assertEqual(['etcd.hosts.1', 'etcd.hosts.2', 'kubernetes.pod_ip', 'postgresql.bin_dir',
'postgresql.data_dir', 'restapi.connect_address'], parse_output(output))
def test_bin_dir_is_empty(self, mock_out, mock_err):
directories.append(config["postgresql"]["data_dir"])
directories.append(config["postgresql"]["bin_dir"])
files.append(os.path.join(config["postgresql"]["data_dir"], "global", "pg_control"))
c = copy.deepcopy(config)
c["restapi"]["connect_address"] = "127.0.0.1:8008"
c["kubernetes"]["pod_ip"] = "::1"
c["consul"]["host"] = "127.0.0.1:50000"
c["etcd"]["host"] = "127.0.0.1:237"
c["postgresql"]["listen"] = "127.0.0.1:5432"
with patch('patroni.validator.open', mock_open(read_data='9')):
schema(c)
output = mock_out.getvalue()
self.assertEqual(['consul.host', 'etcd.host', 'postgresql.bin_dir', 'postgresql.data_dir',
'postgresql.listen', 'restapi.connect_address'], parse_output(output))
@patch('subprocess.check_output', Mock(return_value=b"postgres (PostgreSQL) 12.1"))
def test_data_dir_contains_pg_version(self, mock_out, mock_err):
directories.append(config["postgresql"]["data_dir"])
directories.append(config["postgresql"]["bin_dir"])
directories.append(os.path.join(config["postgresql"]["data_dir"], "pg_wal"))
files.append(os.path.join(config["postgresql"]["data_dir"], "global", "pg_control"))
files.append(os.path.join(config["postgresql"]["data_dir"], "PG_VERSION"))
files.append(os.path.join(config["postgresql"]["bin_dir"], "pg_ctl"))
files.append(os.path.join(config["postgresql"]["bin_dir"], "initdb"))
files.append(os.path.join(config["postgresql"]["bin_dir"], "pg_controldata"))
files.append(os.path.join(config["postgresql"]["bin_dir"], "pg_basebackup"))
files.append(os.path.join(config["postgresql"]["bin_dir"], "postgres"))
files.append(os.path.join(config["postgresql"]["bin_dir"], "pg_isready"))
with patch('patroni.validator.open', mock_open(read_data='12')):
schema(config)
output = mock_out.getvalue()
self.assertEqual([], parse_output(output))
@patch('subprocess.check_output', Mock(return_value=b"postgres (PostgreSQL) 12.1"))
def test_pg_version_missmatch(self, mock_out, mock_err):
directories.append(config["postgresql"]["data_dir"])
directories.append(config["postgresql"]["bin_dir"])
directories.append(os.path.join(config["postgresql"]["data_dir"], "pg_wal"))
files.append(os.path.join(config["postgresql"]["data_dir"], "global", "pg_control"))
files.append(os.path.join(config["postgresql"]["data_dir"], "PG_VERSION"))
c = copy.deepcopy(config)
c["etcd"]["hosts"] = []
del c["postgresql"]["bin_dir"]
with patch('patroni.validator.open', mock_open(read_data='11')):
schema(c)
output = mock_out.getvalue()
self.assertEqual(['etcd.hosts', 'postgresql.data_dir'], parse_output(output))
@patch('subprocess.check_output', Mock(return_value=b"postgres (PostgreSQL) 12.1"))
def test_pg_wal_doesnt_exist(self, mock_out, mock_err):
directories.append(config["postgresql"]["data_dir"])
directories.append(config["postgresql"]["bin_dir"])
files.append(os.path.join(config["postgresql"]["data_dir"], "global", "pg_control"))
files.append(os.path.join(config["postgresql"]["data_dir"], "PG_VERSION"))
c = copy.deepcopy(config)
del c["postgresql"]["bin_dir"]
with patch('patroni.validator.open', mock_open(read_data='11')):
schema(c)
output = mock_out.getvalue()
self.assertEqual(['postgresql.data_dir'], parse_output(output))
def test_data_dir_is_empty_string(self, mock_out, mock_err):
directories.append(config["postgresql"]["data_dir"])
directories.append(config["postgresql"]["bin_dir"])
c = copy.deepcopy(config)
c["kubernetes"] = False
c["postgresql"]["pg_hba"] = ""
c["postgresql"]["data_dir"] = ""
c["postgresql"]["bin_dir"] = ""
schema(c)
output = mock_out.getvalue()
self.assertEqual(['kubernetes', 'postgresql.bin_dir',
'postgresql.data_dir', 'postgresql.pg_hba'], parse_output(output))