Compare commits

...
186 Commits
Author SHA1 Message Date
Sergey Dudoladov 4cc095f913 first commit 2019-09-12 16:58:07 +02:00
anikin-aaandAlexander Kukushkin 3937a8d4fc Fix status code for GET /replica, when replica is starting (#1152)
Close #772, #1128
2019-08-26 11:18:13 +02:00
SoulouandAlexander Kukushkin 53d32f1457 Allow lower values for postgresql configuration (#1148)
* Default values have not been changed
* These minimal values still work properly to boot a (small) cluster

Fixes #1142
2019-08-26 10:48:36 +02:00
Alexander KukushkinandGitHub 0a1d9b0a25 Get rid from distutils module dependency (#1146)
We are using only one function from there, `find_executable()` and it is better to implement a similar function in Patroni rather than add `distutils` module into requirements.txt
2019-08-26 09:38:47 +02:00
Alexander KukushkinandGitHub 3aa3bc3237 Pass statement_timeout=0 in PGOPTIONS when doing pg_rewind (#1155)
It might happen that statement_timeout on the server is set to some small value and one of the statements executed by pg_rewind is canceled.

I already proposed a patch fixing the pg_rewind itself, but it also would be good to have a workaround in Patroni.
2019-08-26 08:43:05 +02:00
msvechlaandAlexander Kukushkin 0d0c4c0a30 Add PATRONICTL_CONFIG_FILE Environment Variable (#1150)
add a `PATRONICTL_CONFIG_FILE` environment variable, which allows configuring the --config-file flag from the environment.
2019-08-26 08:42:24 +02:00
AlexanderandAlexander Kukushkin e9a5d25ef3 Synchronous commit is disabled for rewind user GRANTs (#1145)
SET local synchronous_commit = 'local' before running GRANT
2019-08-23 17:03:02 +02:00
Will ColtonandAlexander Kukushkin 0f7c8b7b09 Fix a command in the docker readme. (#1138)
Fixes #1139
2019-08-06 15:49:32 +02:00
Alexander KukushkinandGitHub 278bf9852b Release 1.6.0 (#1131)
* Implement missing tests and do a few minor fixes
* Bump version to 1.6.0
* Update release notes
2019-08-05 15:08:04 +02:00
Alexander KukushkinandGitHub 0b1b1e3b54 Compatibility with postgresql 12 (#1068)
* use `SHOW primary_conninfo` instead of parsing config file on pg12
* strip out standby and recovery parameters from postgresql.auto.conf before starting the postgres 12

Patroni config remains backward compatible.
Despite for example `restore_command` converted to a GUC starting from postgresql 12, in the Patroni configuration you can still keep it in the `postgresql.recovery_conf` section.
If you put it into `postgresql.parameters.restore_command`, that will also work, but it is important not to mix both ways:
```yaml
# is OK
postgresql:
  parameters:
    restore_command: my_restore_command
    archive_cleanup_command: my_archive_cleanup_command

# is OK
postgresql:
  recovery_conf:
    restore_command: my_restore_command
    archive_cleanup_command: my_archive_cleanup_command

# is NOT ok
postgresql:
  parameters:
    restore_command: my_restore_command
  recovery_conf:
    archive_cleanup_command: my_archive_cleanup_command
```
2019-08-02 16:00:55 +02:00
Alexander KukushkinandGitHub 4a24b79b73 IPv6 support (#1122)
fixes https://github.com/zalando/patroni/issues/1121
2019-08-02 11:34:29 +02:00
Rafia SabihandGitHub 5cc3afc037 Enhance dialogues for scheduled switchover and restart (#1119)
Enhance dialogue for switchover and restart

In case of schedule switchover or restart, mention time if any, when confirming.
2019-08-02 11:21:26 +02:00
Don SeilerandAlexander Kukushkin 5cb7d1bdc1 Grammar fixes for SETTINGS.rst (#1106) 2019-07-26 09:34:42 +02:00
Alexander KukushkinandGitHub 9a94c54cb0 Do a smart comparison of actual and desired primary_conninfo (#1089)
On every replica Patroni periodically opens the recovery.conf file and checks that it contains the correct primary_conninfo.
So far the correctness check was pretty dumb, it was basically doing a full match of strings. That could lead to the restart of the replica when Patroni is "joining" already running postgres process.
Instead of using string comparison we parse the actual primary_conninfo value from the file and check that all parameters are matching with the desired value.

In addition to that we stop reading and parsing recovery.conf of every iteration if the modification time didn't change.
2019-07-01 13:01:45 +02:00
Jan TomsaandAlexander Kukushkin 7d1a5cad03 Allow to specify consul consistency mode (#1094)
Allow users to specify consul consistency mode.
This option will be passed to the Consul client as kwargs https://github.com/zalando/patroni/blob/master/patroni/dcs/consul.py#L213.
The library will then enforce the selected consistency level https://python-consul.readthedocs.io/en/latest/#consul

More about consistency mode here https://www.consul.io/api/features/consistency.html
2019-07-01 11:02:26 +02:00
Jan TomsaandAlexander Kukushkin 1d3fd3ac0b Enable debug logging for GET/OPTIONS API calls together with latency 2019-07-01 10:50:39 +02:00
wilfriedrosetandAlexander Kukushkin 47c3dc2352 patronictl checks if --config value exists (#736) (#1092)
Be verbose about configuration file when the given filename does not exists instead of ignoring silently (which can lead to misunderstanding)
2019-06-27 14:58:07 +02:00
wilfriedrosetandAlexander Kukushkin 78999a2d62 Add fallback value for editor_cmd (#532) (#1091)
Fixes #532
2019-06-27 14:56:57 +02:00
Alexander KukushkinandGitHub 1a6db4f5af Reverse logic around checkpoint_after_promote (#1084)
It will be set to false in the JSON only until the checkpoint actually happened.

The next improvement of https://github.com/zalando/patroni/commit/bba9066315f8dda23e0a28909790a5a3d48d1842
2019-06-17 10:42:31 +02:00
Alexander KukushkinandGitHub fad6d26a3a Small refactoring of postgresql/bootstrap (#1086)
the main purpose of this PR is simplifying #1068

It is mostly necessary for future support of pg12, where there will be no recovery.conf anymore, but `keep_existing_recovery_conf` parameter still needs to be supported due to backward compatibility.
2019-06-17 10:41:13 +02:00
Alexander KukushkinandGitHub 37f03790cc Implement two-step logging (#1080)
A few times we observed that Patroni HA loop was blocked for a few minutes due to not being able to write logs to stderr. This is a very rare condition which we hit so far only on k8s. This commit makes Patroni resilient to such kind of problems. All log messages first are written into the in-memory queue and later they are asynchronously flushed into the stderr or file from a separate thread.

The maximum queue size is configurable and the default value is 1000. This should be enough to keep more than one hour of log messages with default settings and when Patroni cluster operates normally (without big issues).

In case if we hit the maximum size of the queue further logs will be discarded until the queue size will be reduced. The number of discarded messages will be reported into the log later.

In addition to that, the number of non-flushed and discarded messages (if there are any), will be reported via Patroni REST API as:
```json
"logger_queue_size": X,
"logger_records_lost": Y`
```
2019-06-13 14:18:49 +02:00
Alexander KukushkinandGitHub 83e62c2723 Simplify postgresql.reload_config (and fix some bugs) (#1087)
`compare_values` function is already smart enough to handle all tricky cases when the unit is not in `B` or `kB`, but also in blocks. Therefore we don't need to query `wal_segment_size` from pg_settings.
2019-06-13 14:01:37 +02:00
Daniel KuceraandAlexander Kukushkin 638b560cf8 log exceptions caught in Retry (#1081)
Log the final exception when either the number of attempts or the timeout were reached, it will hopefully help to debug some issues when communication to DCS fails
2019-06-11 15:27:14 +02:00
wilfriedrosetandAlexander Kukushkin 2384d9e735 Add API route /health (#1079)
close #119
2019-06-11 15:22:52 +02:00
Kostiantyn NemchenkoandAlexander Kukushkin dcd605ebc8 Update existing_data.rst (#1071) 2019-06-11 15:15:48 +02:00
Alexander KukushkinandGitHub 75926b442e Open trust in pg_hba.conf during bootstrap to localhost (#1075)
previously it was open by mistake to unix_socket only

Fixes https://github.com/zalando/patroni/issues/1072
2019-06-11 15:14:57 +02:00
Alexander KukushkinandGitHub 3b90cc1931 Fix some small issues in the Dockerfile (#1074)
* symlink ~/.config/patroni/patronictl.yaml
* comment out rewind section
2019-05-28 14:47:46 +02:00
Alexander KukushkinandGitHub b291291ff6 Make compare_values compatible with pg12 (#1061)
* integer variables could be specified as floats: work_mem = '30.1GB'
* memory-based units could be in B and MB
* time-based variables now allow microseconds (us)
* vacuum_cost_delay and autovacuum_vacuum_cost_delay converted to real with base unit ms
2019-05-21 16:20:22 +02:00
Alexander KukushkinandGitHub a4bd6a9b4b Refactor postgresql class (#1060)
* Convert postgresql.py into a package
* Factor out cancellable process into a separate class
* Factor out connection handler into a separate class
* Move postmaster into postgresql package
* Factor out pg_rewind into a separate class
* Factor out bootstrap into a separate class
* Factor out slots handler into a separate class
* Factor out postgresql config handler into a separate class
* Move callback_executor into postgresql package

This is just a careful refactoring, without code changes.
2019-05-21 16:02:47 +02:00
Alexander KukushkinandGitHub f1f2389146 A couple of small improvements in acceptance tests (#1057)
* Keep basebackup and wal_archive next to PGDATA in the data directory
* Test bootstrap of standby cluster nodes with custom scripts
2019-05-13 16:33:19 +02:00
Alexander KukushkinandGitHub e54dfa508d Consider sync node as a healthy even when the former leader is ahead (#1059)
Fixes https://github.com/zalando/patroni/issues/1054
2019-05-13 16:32:53 +02:00
Alexander KukushkinandGitHub 4b48653d09 More standby cluster bugfixes (#1053)
1. use the default port is 5432 when only standby_cluster.host is defined
2. check that standby_cluster replica can be bootstrapped without connection to the standby_cluster leader against `create_replica_methods` defined in the `standby_cluster` config instead of the `postgresql` section.
3. Don't fallback to the create_replica_methods defined in the `postgresql` section when bootstrapping a member of the standby cluster.
4. Make sure we specify the database when connecting to the leader.
2019-05-13 14:19:22 +02:00
Alexander KukushkinandGitHub c7db134a20 Make pyscopg2 version parsing more robust (#1052)
non-released version can have unparsable suffixes, for example 2.8.3.dev0
2019-05-13 14:18:56 +02:00
Alexander KukushkinandGitHub bba9066315 Make it possible to run pg_rewind without superuser on pg11+ (#1035)
* expose the current patroni version in DCS
* expose `checkpoint_after_promote` flag in DCS as an indicator that pg_rewind could be safely executed
* other nodes will wait until this flag is set instead of connecting as superuser and issuing the CHECKPOINT
* define `postgresql.authention.rewind` with credentials for pg_rewind in patroni configuration files.
* create user for pg_rewind if postgres is 11+
* grant execute on functions required for pg_rewind to rewind user
2019-05-02 14:07:26 +02:00
vilajitandAlexander Kukushkin f6d29081c9 Enabling kerberos support (#1015)
* make it possible to create users without passwords
* put `krbsrvname` into the connection string if it is specified in the config
* update postgres?.yml example files to mention `krbsrvname`
2019-04-29 09:02:04 +02:00
Alexander KukushkinandGitHub f0b784fe7f Manage pg_ident.conf with Patroni (#1037)
This functionality works similarly to the `pg_hba`:
If the `postgresql.pg_ident` is defined in the config file or DCS, Patroni will write its value to pg_ident.conf, however, if `postgresql.parameters.ident_file` is defined, Patroni will assume that pg_ident is managed from outside and not update the file.
2019-04-23 16:16:53 +02:00
Julien RiouandAlexander Kukushkin 663026c34c Use SSLContext to wrap REST API socket (#1039)
Using `ssl.wrap_socket` is deprecated and was still allowing soon-to-be-deprecated protocols like TLS 1.1.
Now using `SSLContext.create_default_context()` to produce a secure SSL context to wrap the REST API server's socket.
2019-04-23 11:23:22 +02:00
Alexander KukushkinandGitHub 51b085a76d Don't wait until the previous callback finish is kill failed (#1036)
Such wait was happening in the main thread and blocking HA loop.
After all the executor thread was doing absolutely the same.
2019-04-15 15:49:06 +02:00
Cameron DanielandAlexander Kukushkin 74893e7b84 Reload Consul config on SIGHUP (#1030)
It is especially useful when somebody is changing the value of `token`
2019-04-15 15:00:38 +02:00
Julien RiouandAlexander Kukushkin 0e0b364302 Add read-only and read-write API routes (#1038)
Patroni is great behind a load balancer like HAProxy. API routes are handy to direct the traffic to a valid node depending on its role. We could have one route for writes directed to the primary node and one route for reads directed to the replicas. In a two nodes setup, when we lose a node, there's one host left: the primary. Then, the read traffic will be dropped, even if the primary can handle it. This commit adds read-only and read-write routes. Read-only route enables reads on the primary. Read-write route is an alias for '/master', '/primary' or '/leader' route.
2019-04-15 14:49:54 +02:00
Alexander KukushkinandGitHub 51b02e65a5 Don't set archive_mode to off during the custom bootstrap (#1025)
As @ants complained on Slack, it breaks the workflow when the same location is used for bootstrap and further archiving.
For the pg_upgrade we can achieve the same results by modifying postgres config in the upgrade script, which is part of spilo.
2019-04-15 14:31:02 +02:00
Alexander KukushkinandGitHub 7c0c9599fc Remove psycopg2 from requirements (#1023)
Recently released psycopg2 split into two different packages, psycopg2, and psycopg2-binary which could be installed at the same time into the same place on the filesystem. In order to decrease dependency hell problem, we let a user choose how to install psycopg2. There are a few options available and it is reflected in the documentation.

This PR also changes the following behavior:
* `pip install patroni` will fail if psycopg2 is not installed
* Patroni will check psycopg2 upon start and fail if it can't be found or outdated.

Closes https://github.com/zalando/patroni/issues/1021
2019-04-15 14:30:16 +02:00
joe-tssandAlexander Kukushkin cf0d712450 Grant deletecollection to patroni serviceaccount (#1033)
Closes #1032
2019-04-11 15:17:06 +02:00
Sharoon ThomasandAlexander Kukushkin d418a9449e scheduled_at needs a value for manual_failover (#1024)
The variable scheduled_at may be undefined for a manual failover where there is an exception raised trying to switchover with REST API.
2019-04-08 12:35:15 +02:00
Alexander KukushkinandGitHub 6909ce0c7a Release 1.5.6 (#1020)
* Update release notes
* Bump version
2019-04-03 14:44:31 +02:00
Alexander KukushkinandGitHub cd9d9ca0c3 Make sure we don't enforce ssl_version (#1010)
Fixes https://github.com/zalando/patroni/issues/1009
2019-04-02 16:49:32 +02:00
Alexander KukushkinandGitHub a0a2da238e Couple of minor improvements (#1019)
1. Fix race condition on shutdown. It is very annoying when you cancel behave tests but postgres remains running.
2. Dump pg_controldata output to logs when "recovering" stopped postgres. It will help to investigate some annoying issues.
2019-04-02 16:49:21 +02:00
Pavlo GolubandAlexander Kukushkin b53a29c022 Fix unit-tests for Windows (#1014)
Closes #1013
2019-04-02 13:58:17 +02:00
Alexander KukushkinandGitHub e38fe78b56 Fix callbacks behavior (mostly for standby cluster) (#998)
First of all, this patch changes the behavior of `on_start`/`on_restart` callbacks, they will be called only when postgres is started or restarted without role changes. In case if the member is promoted or demoted only the `on_role_change` callback will be executed. `on_role_change` was never called for standby leader, only `on_start`/`on_restart` and with a wrong role argument.
Before that `on_role_change` was never called for standby leader, only `on_start`/`on_restart` and with a wrong role argument.

In addition to that, the REST API will return standby_leader role for the leader of the standby cluster.

Closes https://github.com/zalando/patroni/issues/988
2019-03-29 10:28:07 +01:00
Lukas VogelandAlexander Kukushkin e059e30560 Ingore VSCode files (#1007)
Fixes #1008
2019-03-22 16:26:37 -04:00
Alexander KukushkinandGitHub 680444ae13 Reduce lock time taken by dcs.get_cluster() (#989)
`dcs.cluster` and `dcs.get_cluster()` are using the same lock resource and therefore when get_cluster call is slow due to the slowness of DCS it was also affecting the `dcs.cluster` call, which in return was making health-check requests slow.
2019-03-12 22:37:11 +01:00
Alexander KukushkinandGitHub 92720882aa Reset is_leader flag for every removal of leader key (#990)
This is the next improvement of #777
2019-03-12 22:10:46 +01:00
Alexander KukushkinandGitHub 13c88e8b7a Replace self-execute with multiprocessing.Process (#994)
In addition to that transfer postmaster pid to Patroni process with the help of multiprocessing.Pipe instead of using stdin-stdout pipes.

Closes https://github.com/zalando/patroni/issues/992
2019-03-12 10:40:37 +01:00
Alexander KukushkinandGitHub 4a4258fc3f Mock external resources (#995)
unit tests should not accidentally hit running Postgres, DCS or filesystem unless we want it explicitly.
2019-03-12 10:39:42 +01:00
Ants AasmaandAlexander Kukushkin 2204454094 Remove unnecessary usage of relpath (#1002)
`os.path.relpath` depends on being able to resolve the working directory.
This will fail if Patroni is started in a directory that is later unlinked from the filesystem, creating an unnecessary exception when loading from DCS.
2019-03-11 12:31:06 +01:00
Alexander KukushkinandGitHub 9e19b43869 Rename cluster name to demo (#1000)
* Assign hostname to haproxy container
* Tune vim config
2019-03-11 10:57:26 +01:00
Julien TachoiresandAlexander Kukushkin 13f7aede61 Wait for callback end if it could not be killed (#985)
that could happen if the script is running under a sudo
2019-03-11 10:35:36 +01:00
Julien TachoiresandAlexander Kukushkin 8a7ba57457 Clean target directory when pg_wal|pg_xlog is a symlink (#997) 2019-03-11 10:33:46 +01:00
Alexander KukushkinandGitHub c64d51f79c Better support for static etcd cluster (#986)
if the `etcd.use_proxies` is set to true, Patroni will stick to the list of hosts specified in the `etcd.hosts` and avoid doing topology discovery. Such mode might be useful when you know that you connect to the etcd cluster via the set of proxies or when th etcd cluster has static topology.
2019-03-07 11:36:36 +01:00
Alexander KukushkinandGitHub f0990532dc Update docker-compose demo cluster (#980)
1. Multi-stage build with an extensive cleanup of useless files and optional image compression
2. Start three-node etcd cluster
3. Start three-node Patroni cluster
4. One container with haproxy
5. All container names are prefixed with "demo-" and don't have suffixes
6. Decommission dev_patroni_cluster.sh script, docker-compose is now standard de-facto.
7. Provide more examples in the docker/README.md
2019-03-07 11:32:03 +01:00
Alexander KukushkinandGitHub e670122c80 Use create_replica_methods from standby_cluster for replica bootstrap (#981)
It might happen that the standby cluster is configured to be created and replay WAL files from the different source than when it is running not in standby mode.  This is necessary to avoid writing WAL files and backups into the old place after promotion.

The easiest way to achieve such behavior is passing RemoteMember object to `Postgresql.clone` method instead of the usual Member object.
2019-02-21 11:37:50 +01:00
Alexander KukushkinandGitHub c6e70a9910 Release 1.5.5 (#979)
* Bump version
* Update release notes
2019-02-15 16:14:39 +01:00
Alexander KukushkinandGitHub 0ec1760397 Don't write primary_conninfo into recovery.conf for wal only standby cluster (#971)
It is useless and makes postgres to generate a lot of errors
2019-02-15 13:35:34 +01:00
Alexander KukushkinandGitHub 317721991b Fix handling of PATRONI_*_PASSWORD environment variables (#970)
Bug was introduced in https://github.com/zalando/patroni/pull/947 and https://github.com/zalando/patroni/pull/500
2019-02-15 13:35:22 +01:00
Alexander KukushkinandGitHub 0c516de147 Create headless service associated with $SCOPE-config endpoint (#958)
if there is no service defined k8s assumes that endpoint is orphaned and removes it.
Patroni tries to create the service only in case if use_endpoints is enabled if the following cases:
1. Upon start
2. When it tries to (re-)create the config endpoint

If for some reason creation of the service has failed, Patroni will retry it on every cycle of HA loop. Usually it fails due to lack of permissions and if you don't want to give such permissions to the service account used by Patroni, you can create the service explicitly in the deployment manifest.
2019-02-15 13:35:04 +01:00
Michael BanckandAlexander Kukushkin 073074f83e Run coverage as python -m coverage (#968)
Depending on the platform the coverage binary might not always be available under the standard name.
2019-02-13 16:02:12 +01:00
Michael BanckandAlexander Kukushkin 345e6d3131 Copy away output directories of failed acceptance tests. (#967)
And dump logs on travis from only failed features
2019-02-13 16:00:15 +01:00
Michael BanckandAlexander Kukushkin d01a9bdcd5 Change base port for acceptance tests from 5440 to 5360 (#966) 2019-02-13 15:59:13 +01:00
Alexander KukushkinandGitHub 10bbf0c3c5 Always use replication=1, otherwise it is considered a logical walsender (#952)
Fixes: https://github.com/zalando/patroni/issues/894
Fixes: https://github.com/zalando/patroni/issues/951
2019-01-30 12:38:51 +01:00
Alexander KukushkinandGitHub 4304560ce2 Adjust read timeout for leader watch blocking query (#950)
According to the Consul documentation the actual response timeout is increased by a small random amount of additional wait time added to the supplied maximum wait time to spread out the wake up time of any concurrent requests. It adds up to wait / 16 additional time to the maximum duration.
In our case we will add wait/15 or 1 second depending on what is bigger.

Fixes: https://github.com/zalando/patroni/issues/945
2019-01-30 12:38:24 +01:00
Alexander KukushkinandGitHub 254ee2acfc Show information about timelines in patronictl list (#949)
This information will help to detect stale replicas.

In addition to that Host will include ':{port}' if the port value isn't default or more than one member running on the same host.

Fixes: https://github.com/zalando/patroni/issues/942
2019-01-30 12:37:51 +01:00
Alexander KukushkinandGitHub 739329b590 Make it possible to automatically reinit the former master (#948)
If the pg_rewind is disabled or can't be used, the former master could fail to start as a new replica due to diverged timelines. In this case, the only way to fix it is wiping the data directory and reinitializing.

So far Patroni was able to remove the data directory only after failed attempt to run pg_rewind. This commit fixes it.
If the `postgresql.remove_data_directory_on_diverged_timelines` is set, Patroni will wipe the data directory and reinitialize the former master automatically.

Fixes: https://github.com/zalando/patroni/issues/941
2019-01-30 12:37:21 +01:00
Étienne MandAlexander Kukushkin bd2c54581a Add ETCD_(PROTOCOL|USERNAME|PASSWORD) env variables (#947)
Fix #944
2019-01-30 12:36:50 +01:00
Maxim IvanovandAlexander Kukushkin f0b12b7e2e Document create_replicas_methods in standby_cluster section (#939)
Fixes https://github.com/zalando/patroni/issues/935
2019-01-30 12:36:24 +01:00
Étienne MandAlexander Kukushkin 93d157dea3 Document how to start Patroni with an existing data directory (#918) 2019-01-30 12:35:57 +01:00
Alexander KukushkinandGitHub 2c128520cf Python34 compatibility (#933)
and some other minor fixes.

Closes https://github.com/zalando/patroni/issues/932
2019-01-16 14:40:05 +01:00
Alexander KukushkinandGitHub 381a5b80d2 Release 1.5.4 (#931)
* Bump version
* Update release notes
* Make it possible to configure registration of Service in Consul via env variables
2019-01-15 12:14:19 +01:00
Alexander KukushkinandGitHub 71dae6a905 Optionally consider node not healthy if it is not on the latest timeline (#892)
The latest timeline is calculated from the `/history` key in DCS. In case there is no such key or it contains some garbage we consider the node healthy.
Closes https://github.com/zalando/patroni/issues/890
2019-01-15 11:16:30 +01:00
Alexander KukushkinandGitHub cf34fb3934 Relax requirements on superuser credentials (#930)
libpq allows opening connection without explicitly specifying neither username nor password. Depending on situation it would rely either on `pgpass` file or trust authentication method in pg_hba.conf.

Since pg_rewind is also using libpq, it could work the same way.

Fixes https://github.com/zalando/patroni/issues/928
2019-01-15 11:15:35 +01:00
Alexander KukushkinandGitHub e080ded44b Make logging configurable via YAML file (#927)
It allows changing logging settings in runtime by updating config and doing reload or sending `SIGHUP` to the Patroni process.
Important! Environment configuration names related to logging were renamed and documentation accordingly updated. For compatibility reasons Patroni still accepts `PATRONI_LOGLEVEL` and `PATRONI_FORMAT`, but some other variables related to logging, which were introduced only
recently (between releases), will stop working. I think it is ok, since we didn't release the new version yet and therefore it is very unlikely that somebody is using them except authors of corresponding PRs.

Example of log section in the config file:
```yaml
log:
  dir: /where/to/write/patroni/logs  # if not specified, write logs to stderr
  file_size: 50000000  # 50MB
  file_num: 10  # keep history of 10 files
  dateformat: '%Y-%m-%d %H:%M:%S'
  loggers:  # increase log verbosity for etcd.client and urllib3
    etcd.client: DEBUG
    urllib3: DEBUG
```
2019-01-15 08:42:13 +01:00
jouirandAlexander Kukushkin dec3656f6e Redirect HTTPServer exceptions to logger (#900) (#925)
By default they were written to stdout
2019-01-15 08:37:06 +01:00
Alexander KukushkinandGitHub 1e2d89fa58 Apply 5 second backoff when loading global config up on start (#922)
It doesn't make much sense to hammer DCS when we just starting up.
Fixes https://github.com/zalando/patroni/issues/919
2019-01-14 14:55:56 +01:00
Alexander KukushkinandGitHub 994863c18d Refactor wait_for_user_backends_to_close method (#917)
1. Log only debug level messages on any kind of error
2. Update regexp for matching postgres aux processes to make it compatible with postgres 11

Fixes https://github.com/zalando/patroni/issues/914
2019-01-14 14:55:45 +01:00
Alexander KukushkinandGitHub 3fce982909 Set archive_mode to off during the custom bootstrap (#911)
We want to avoid archiving WALs and history files until the cluster is fully functional. It should really help if the custom bootstrap involves pg_upgrade.
2019-01-14 14:55:23 +01:00
Lucas CapistrantandAlexander Kukushkin d306092cbc Explicitly secure rw perms for recovery.conf at creation time (#910)
We don't want anybody except patroni/postgres user reading this file, it contains replication user and password.
2019-01-14 14:22:04 +01:00
Dmitry DolgovandAlexander Kukushkin 11f7ceb521 Do not check types of standby_cluster configuration (#924)
Simply allow valid keys
2019-01-14 14:16:15 +01:00
bradnicholsonandAlexander Kukushkin 05a13839aa Update replica_bootstrap.rst (#915)
Add some docs about replication slots for standby clusters
2019-01-14 12:57:21 +01:00
Étienne MandAlexander Kukushkin 04ac199fc8 Single quotes are mandatory around each host in PATRONI_ETCD_HOSTS (#926)
Otherwise YAML parser fails
2019-01-14 11:56:15 +01:00
anikin-aaandAlexander Kukushkin 0be8a9527b possibility to set logdatefmt via env. (#904)
The value could be configured via `PATRONI_LOGDATEFMT` environment variable. The default value is `%Y-%m-%d %H:%M:%S`
2019-01-14 08:46:38 +01:00
Pavel KirillovandAlexander Kukushkin 929ff08bfd Service deregister timeout must be in Go time format (#893) 2018-12-21 15:42:15 +01:00
Cody CoonsandAlexander Kukushkin 7bc8d0aac9 Removed stderr pipe to stdout on pg_ctl process (#896)
Inheriting stderr from the main Patroni process allows all Postgres logs to be seen along with all patroni logs. This is very useful in a container environment as Patroni and Postgres logs may be consumed using standard tools (docker logs, kubectl, etc).

In addition to that, this change fixes a bug with Patroni not being able to catch postmaster pid when postgres writing some warnings into stderr
2018-12-21 15:41:34 +01:00
Lucas CapistrantandAlexander Kukushkin f3da6de129 Add ability to configure app logs to be written to a file (#903)
It gives users the option to send Patroni application logs to a File instead of Standard Out. There are three environment variables that can be set to enable and configure file logging.
1. `PATRONI_FILE_LOG_DIR`: Path to a directory that is writeable by the executing user. Having this variable set is what activates file logging.
2. `PATRONI_FILE_LOG_NUM`: This is a rolling file logger. This variable dictates how many log files are retained.
3. `PATRONI_FILE_LOG_SIZE`: This variable dictates the size at which the logs will roll.

If `PATRONI_FILE_LOG_DIR` is not set than Patroni will log to stderr (default behavior does not change)

Closes https://github.com/zalando/patroni/issues/902
2018-12-21 15:38:29 +01:00
Alexander KukushkinandGitHub 491f230711 Release 1.5.3 (#889)
* Bump version
* Update release notes
2018-12-03 17:12:53 +01:00
Alexander KukushkinandGitHub f1d7ccf36e Make sure we refresh session at least once per HA loop (#880)
Fixes https://github.com/zalando/patroni/issues/879
2018-12-03 16:35:14 +01:00
Kostiantyn NemchenkoandAlexander Kukushkin 96ea01bee4 Fix kubernetes demo files (#885)
- Update postgres docker image to the latest 11 version.

- Remove empty lines inside the `RUN` command to make the Dockerfile compatible with future docker versions.

- Set the `PATRONI_KUBERNETES_POD_IP` environment variable, which is required when _use_endpoints_ is enabled. Otherwise, the `KeyError` is raised [here](https://github.com/zalando/patroni/blob/master/patroni/dcs/kubernetes.py#L95).

- Set `EDITOR` environment variable to make configuration changes via `patronictl edit-config`.
2018-12-03 15:46:25 +01:00
Alexander KukushkinandGitHub e684ca66e5 Compatibility with postgres 9.3 (#882)
use replication=1 instead of replication='database' when opening replication connection, 9.3 doesn't understand it
2018-11-30 15:46:05 +01:00
Alexander KukushkinandGitHub 1a0876e5ca Refactor acceptance tests to improve stability (#884)
Hope it will crash less often when executed on travis against k8s
2018-11-30 12:40:56 +01:00
Alexander KukushkinandGitHub 9bf074acfb Compatibility with python3 (#883)
Change of `loop_wait` was causing Patroni to disconnect from zookeeper and never reconnect back. The error was happening only with python3 due to a difference in implementation of `select.select` function.
2018-11-30 11:40:34 +01:00
Alexander KukushkinandGitHub f8f928420d Release 1.5.2 (#875)
* Update release notes
* Bump version
2018-11-26 10:31:14 +01:00
Shea StewartandAlexander Kukushkin 6519a192b1 add openshift customizations, templates, and test (#871)
- It modifies the Dockerfile and entrypoint slightly to allow for OpenShift SCCs to operate correctly
- It adds 2 template examples that can be easily modified by changing parameters

Fixes #572
2018-11-21 18:01:39 +01:00
Alexander KukushkinandGitHub 8c7e1892ee touch_member method should not raise exceptions (#859)
Fixes https://github.com/zalando/patroni/issues/853
2018-11-21 12:51:52 +01:00
Lardière SébastienandAlexander Kukushkin a1ba2cdca7 Add confd template for pgbouncer (#844) 2018-11-21 12:03:22 +01:00
Kostiantyn NemchenkoandAlexander Kukushkin ce9c7bdadc Describe Consul registration parameters (#870)
Mention Consul related parameters introduced by #802
2018-11-21 12:00:40 +01:00
Alexander KukushkinandGitHub fb01aaebc5 Compatibility with kazoo-2.6.0 (#872)
Recently 2.6.0 was release which changes the way how create_connection method is called. Before it was passing two arguments, and in the new version all argument names are specified explicitly.
2018-11-19 14:26:20 +01:00
alago197andAlexander Kukushkin a13cc8b847 Update SETTINGS.rst with connect_address clarifications (#858) 2018-11-12 16:56:51 +01:00
lwsboxandAlexander Kukushkin bd9f30372e fix bug: change pip to pip3 (#851)
should use python3 to install in postgres10 image.
2018-11-05 14:17:22 +01:00
Josh BerkusandAlexander Kukushkin d247b5ae17 Fix several build problems with the Docker image for testing Kubernet… (#735)
1. Update to Postgres 10
2. Install most of the python modules from deb packages
3. Do *not* upgrade pip
2018-11-04 08:31:11 +01:00
Alexander KukushkinandGitHub b4f35ecca0 Release 1.5.1 (#846)
* Bump version
* Update release notes
2018-11-01 16:18:41 +01:00
Alexander KukushkinandGitHub 0f666e69f3 Prefix system tables, views and functions with pg_catalog (#845)
and implement missing unit tests
2018-11-01 16:17:40 +01:00
Alexander KukushkinandGitHub 2efd97baab Permanent replication slots (#819)
Permanent replication slots are preserved on failover/switchover, that is Patroni on the new primary will create configured replication slots right after doing promote.

Slots could be configured with the help of `patronictl edit-config`.
The initial configuration could be also done in the `bootstrap.dcs`

```yaml
slots:
  permanent_physical_1:
    type: physical
  permanent_logical_1:
    type: logical
    database: foo
    plugin: pgoutput
```

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.

Closes https://github.com/zalando/patroni/issues/656
2018-10-31 11:37:42 +01:00
Alexander KukushkinandGitHub c65c4f1ffe Round-robing across all masters in pause mode if DCS is not accessible (#842)
Regression was introduced in https://github.com/zalando/patroni/commit/90cf930036a9d5249265af15d2b787ec7517cf57

Fixes https://github.com/zalando/patroni/issues/841
2018-10-30 16:48:53 +01:00
SrikanthandAlexander Kukushkin 2264190e79 Add pre-command to start watchdog (#835)
Add `ExecStartPre` commands to systemd unit to help start watchdog devices.
2018-10-26 07:55:01 +01:00
Alexander KukushkinandGitHub f70edefc65 A few bugfixes in the "standby cluster" workflow (#823)
* Always run `pg_rewind` against the remote master
* Always use the remote master as the source when "recovering" stopped standby leader
* Use remote master as the source when "recovering" the node in the unhealthy cluster
* Use the local dbname as the fallback when doing `pg_rewind` from the remote master
*  `no_replication_slot` is the allowed key in the `RemoteMember` object
* Make it possible to "bootstrap" the new `standby_cluster` with existing (and valid) data directory. There is one prerequisite though, there should be no `patroni.dynamic.json` file in it!
2018-10-09 13:30:48 +02:00
Yogesh SharmaandAlexander Kukushkin 6567f509b1 Add pgbackrest support (#1) (#822)
* pgbackrest support

pgBackrest can restore in existing $PGDATA folder, this allows speedy restore as files which have not changed since last backup are skipped, to support this feature new param keep_data has been introduced. When keep_data=True, cleanup of $PGDATA will be skipped.

Patroni passes some extra parameters to custom_replica_methods when calling, this causes an error due to pgbackrest strict parameter checking. New param no_params=True can be set to skip parameters passing.

Fixes https://github.com/zalando/patroni/issues/625
2018-10-08 19:00:30 +02:00
Alexander KukushkinandGitHub 534829d617 Release 1.5.0 (#809)
Update release notes and bump version
2018-09-20 16:29:00 +02:00
Alexander KukushkinandGitHub 76d1b4cfd8 Minor fixes (#808)
* Use `shutil.move` instead of `os.replace`, which is available only from 3.3
*  Introduce standby-leader health-check and consul service
* Improve unit tests, some lines were not covered
* rename `assertEquals` -> `assertEqual`, due to deprecation warning
2018-09-19 16:32:33 +02:00
Pavel GolubandAlexander Kukushkin 3d76a013a7 Support for Windows (#799)
Postgres on Windows is using different signals, backslashes as file separators and some of the functions and syscalls are not available there.
2018-09-19 13:50:36 +02:00
Pavel KirillovandAlexander Kukushkin 2e9cb412e4 Register service in consul (#802)
Кegister service 'scope_name' with tag 'master' or 'replica'

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

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

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

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

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

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

Issue a new minor release.

Fixes https://github.com/zalando/patroni/issues/776
2018-08-14 17:08:08 +02:00
Dmitry DolgovandGitHub b282a0f254 Add "cluster_unlocked" field (#764)
Add a field to an api to figure out if a master is there from patroni point
of view. It can be useful, when you have an alert, based on Auto Scaling
Groups, and then ASG decided to shutdown the current master, spin up a
new instance but the current master shutdown is stuck. In this situation
the current master is no longer a part of ASG, but patroni and Postgres
are still alive on the instance, which means a new replica will not be
promoted yet - this will lead to a false alert, saying that your cluster
doesn't have any master node.
2018-08-13 14:02:01 +02:00
Oleksii KliukinandAlexander Kukushkin 5e7345a2ca Release notes 1.4.5 (#762)
bump version update release notes
2018-08-03 17:02:11 +02:00
Don SeilerandAlexander Kukushkin 502094ee79 Log config change or not (#731)
This adds INFO log messages that clearly state if configuration values were seen as changed by Patroni after SIGHUP/reload and warrant reloading (or if nothing was changed an no reloading is necessary).

This ended up being a lot simpler than I had imagined once I found postgresql.py:reload_config().

I add a log line in config.py:reload_local_configuration() since that function will short-circuit the process early if the local config wasn't changed. But the final determination of whether or not values have changed and need reloading is in postgresql.py:reload_config().
2018-08-03 17:00:57 +02:00
Alexander KukushkinandGitHub 0c1ae6fbeb Respond 200 to master health-check only if update_lock was successful (#713)
If Patroni gets partitioned it starts receiving stale information from DCS.
We can't use this information to determine that we have the leader key.
Instead, we will record in Ha object the actual state of acquire/update lock and report as a leader only if it was successful.

P.S. despite responding with 200 on `GET /master` postgres was still running read-only.
2018-08-03 17:00:01 +02:00
Alexander KukushkinandGitHub 2fd2556050 Set role to demoted if postgres isn't running and no recovery.conf (#757)
In really rare cases it was causing following behavior:
```
2018-07-31 10:35:30,302 INFO: starting as a secondary
2018-07-31 10:35:30,309 INFO: Lock owner: postgresql0; I am postgresql1
2018-07-31 10:35:30,310 INFO: Demoting master during restarting after failure
2018-07-31 10:35:30,381 INFO: postmaster pid=17709
2018-07-31 10:35:30,386 INFO: lost leader lock during restarting after failure
2018-07-31 10:35:30,388 ERROR: Exception during CHECKPOINT
```
2018-08-03 16:59:04 +02:00
Oleksii KliukinandAlexander Kukushkin d47049ce0e Fix condition for the replica start due to pg_rewind in paused state. (#754)
Avoid starting the replica that had already executed pg_rewind before.

Fixes in #753
2018-08-03 16:45:33 +02:00
Henning JacobsandGitHub 2f7c53031c Python 3.6 and 3.7 are now supported, too (#752) 2018-07-24 10:51:25 +02:00
Christoph BergandHenning Jacobs a2c6ed5504 async is a keyword in python3.7 (#751)
* async is a keyword in python3.7

Setting up patroni (1.4.4-1) ...
    File "/usr/lib/python3/dist-packages/patroni/ha.py", line 610
      'offline':          dict(stop='fast', checkpoint=False, release=False, offline=True, async=False),
                                                                                               ^
  SyntaxError: invalid syntax

Fix #750 by replacing dict member "async" with "async_req".

* requirements.txt: Update for new kubernetes version compatible with 3.7
2018-07-23 20:42:33 +02:00
Oleksii KliukinandAlexander Kukushkin 00c2e1c2d0 Grant delete on endpoints and configmaps in RBAC. (#749)
'patronictl remove' deletes the cluster configuration (stored either in configmaps or endpoints) and cannot be run from the postgres pod w/o 'delete' on those objects being granted to the pod service account.
2018-07-23 20:39:46 +03:00
Don SeilerandAlexander Kukushkin f5927bad70 Add EnvironmentFile directive (#746)
Add an EnvironmentFile directive to read in a configuration file with environment variables. The "-" prefix means it can proceed if the file doesn't exist.

This would allow users to keep sensitive information like the SUPERUSER/REPLICATION passwords in the config file separate from a YAML file that might be deployed from source control.
2018-07-23 20:31:47 +03:00
Alexander KukushkinandOleksii Kliukin 26466237b9 Update docker-compose example to postgres 10 (#737)
Some other changes are related to the new version of confd, which now
requires specifying etcd url instead of etcd host.
2018-07-23 16:41:17 +02:00
Tony SorrentinoandOleksii Kliukin c8f9199988 Added setting state to "stopped" when a member is stopped in Ha.shutdown (#733)
Changes by @tonys66, review by @CyberDem0n
2018-07-23 14:59:39 +02:00
Alexander KukushkinandOleksii Kliukin 2356af679b Convert query params from list to dict (#744)
Patroni is relying on params to determinte timeout and amount of retries when executing api requests to consul. Starting from v1.1.0 python-consul changed internal API and started
using `list` instead of `dict` to pass query parameters. Such change broke "watch" functionality.

Fixes https://github.com/zalando/patroni/issues/742 and
https://github.com/zalando/patroni/issues/734
2018-07-23 14:56:51 +02:00
Ants AasmaandOleksii Kliukin 3b633abd91 Improve logging when stale postmaster.pid matches running process (#738)
Currently the informational message logged is beyond confusing. This
improves the logging so there is some indication what this message is
about and that it is somewhat normal. Changes by @ants
2018-07-17 16:46:22 +02:00
alago197andOleksii Kliukin 936a4238fb Update some descriptions for the REST API endpoints (#729)
* Update some descriptions for the REST API endpoints

By @alago197
2018-07-10 15:40:53 +02:00
Don SeilerandOleksii Kliukin 50a8114d0b Use enforced minimums in postgresX.yml files (#730)
Fix the discrepancy for the values of max_wal_senders and max_replication_slots between the sample postgres.yml files and hard-coded defaults in Patroni, bumping the former to 10.
Contributed by @dtseiler
2018-07-04 10:08:54 +02:00
Don SeilerandAlexander Kukushkin 4e8709b266 Adding reload functionality (#726)
This allows the config to be reloaded via `systemctl reload patroni`, sending SIGHUP to the patroni process. Tested on CentOS.
2018-06-30 23:16:42 +02:00
Alexander KukushkinandGitHub 4128cba628 max_worker_processes parameter was introduced only in 9.4 (#724)
exclude it from the list on 9.3 when building effective configuration
2018-06-26 13:48:16 +01:00
Don SeilerandAlexander Kukushkin 959f254bfb Adding patronictl reload functionality to reload from yaml config file (#716)
Fixes https://github.com/zalando/patroni/issues/715
2018-06-20 10:09:10 +02:00
Alexander KukushkinandGitHub 8a3b78ca7b Rest api thread can raise an exception during shutdown (#711)
catch it and report
2018-06-14 13:17:50 +02:00
Oleksii KliukinandGitHub 41e5f58f2b Describe synchronous_mode_strict (#710)
* Describe synchronous_mode_strict

Per https://github.com/zalando/patroni/issues/709
2018-06-13 11:12:22 +02:00
Dmitry DolgovandGitHub f0d23b0b14 Merge pull request #706 from zalando/feature/rename-create-replica-method
Rename create_replica_method to create_replica_methods
2018-06-12 14:16:54 +02:00
Alexander KukushkinandGitHub cbd0a759c0 Relax kubernetes module version (#701)
Patroni is proven to work with 2.0.0, 3.0.0 and 6.0.0
2018-06-12 14:11:00 +02:00
Alexander KukushkinandGitHub aadd39b0a4 Do crash recovery only when we sure that postgres was running as master (#707)
pg_controldata reports in this case:
* 'in production'
* 'shutting down'
* 'in crash recovery'
2018-06-12 14:09:09 +02:00
Henning JacobsandAlexander Kukushkin 2537147810 #694 handle configuration error (#695)
It is possible to change a lot of parameters in runtime (including `restapi.listen`) by updating Patroni config file and sending SIGHUP to Patroni process.

If something was misconfigured it was throwing a weird exception and breaking `restapi` thread.

This PR improves friendliness of error message and avoids breaking of `restapi`.
2018-06-12 14:08:38 +02:00
Alexander KukushkinandGitHub e939304001 Take and apply some parameters from controldata when starting as replica (#703)
* Take and apply some parameters from controldata when starting as replica

https://www.postgresql.org/docs/10/static/hot-standby.html#HOT-STANDBY-ADMIN
There is set of parameters which value on the replica must be not smaller than on the primary, otherwise replica will refuse to start:
* max_connections
* max_prepared_transactions
* max_locks_per_transaction
* max_worker_processes

It might happen that values of these parameters in the global configuration are not set high enough, what makes impossible to start a replica without human intervention. Usually it happens when we bootstrap a new cluster from the basebackup.

As a solution to this problem we will take values of above parameters from the pg_controldata output and in case if the values in the global configuration are not high enough, apply values taken from pg_controldata and set `pending_restart` flag.
2018-06-12 14:04:32 +02:00
Chris FraserandAlexander Kukushkin aa18f70466 If set, use LD_LIBRARY_PATH when starting postgres (#698)
Fixes #697
2018-06-12 14:00:48 +02:00
Alexander KukushkinandGitHub e405e4e03c Workaround to sporadic unit-test failures (#696)
Fixes https://github.com/zalando/patroni/issues/691
2018-06-12 14:00:10 +02:00
erthalion 3d80e49b38 Rename also in settings docs 2018-06-12 13:28:30 +02:00
erthalion d037aa8afd Rename create_replica_method to create_replica_methods
To make it clear that it's actually an array
2018-06-12 11:33:13 +02:00
Björn AlbersandAlexander Kukushkin e5f2511764 Add WorkingDirectory to systemd sample config. (#686)
Otherwise `initdb` fails because it tries to create the data directory in the root directory where the postgres user has no permissions.
2018-06-04 16:36:41 +02:00
Alexander KukushkinandGitHub 1de7c78c04 Release 1.4.4 (#683)
bump version and update release notes
2018-05-22 14:46:19 +02:00
Alexander KukushkinandGitHub 041015037e Sync replication slots when we noticed a new postmaster process (#677)
Fixes: https://github.com/zalando/patroni/issues/674
2018-05-18 16:32:06 +02:00
Alexander KukushkinandGitHub 856552bd61 Sync replication slots and verify sysid after coming out of pause (#678)
Fixes https://github.com/zalando/patroni/issues/568
and https://github.com/zalando/patroni/issues/674
2018-05-18 12:18:49 +02:00
Oleksii KliukinandAlexander Kukushkin 4ce539ba1b Allow options to the basebackup built-in method. (#604)
Options should be specified in the basebackup section, which is optional.
2018-05-18 12:18:35 +02:00
Oleksii KliukinandAlexander Kukushkin 1043376e6b Do not exit when encountering invalid system ID. (#669)
Do not exit when the cluster system ID is empty or the one that doesn't pass the validation check. In that case, the cluster most likely needs a reinit; mention it in the result message.
Avoid terminating Patroni, as otherwise reinit cannot happen.
2018-05-18 11:48:15 +02:00
Alexander KukushkinandGitHub ed479fe585 Don't demote master if failed to update leader key in pause (#668)
Fixes https://github.com/zalando/patroni/issues/659
2018-05-18 11:19:56 +02:00
Alexander KukushkinandGitHub 5ce18a8045 Improve protection of DCS being accidentally wiped (#680)
We already have a lot of logic in place to prevent failover in such case and restore all keys, but an accidental removal of `/config` key was effectively switching off pause mode for 1 cycle of HA loop.
2018-05-18 11:18:58 +02:00
Alexander KukushkinandGitHub 5296336f4a BUGFIX: postmaster start can fail if pid from postmaster.pid is alive (#681)
Upon start postmaster process performs various safety checks if there is a postmaster.pid file in the data directory. Although Patroni already detected that the running process corresponding to the postmaster.pid is not a postmaster, the new postmaster might fail to start, because it thinks that postmaster.pid is already locked.
Important!!! Unlink of postmaster.pid isn't an option in this case, because it has a lot of nasty race conditions.
Luckily there is a workaround to this problem, we can pass the pid from postmaster.pid in the `PG_GRANDPARENT_PID` environment variable and postmaster will ignore it.

More likely to hit such problem if you run Patroni and postgres in the docker container.
2018-05-18 11:18:27 +02:00
Cody CoonsandAlexander Kukushkin 3eeb4ed979 Added check for empty subsets (#670)
On Kubernetes 1.10.0 I experienced an issue where calls to `patch_or_create` were failing when bootstraping a cluster. The call was failing because `self._leader_observed_subsets` was `None` instead of `[]`.
2018-04-26 16:38:19 +02:00
Alexander KukushkinandGitHub 84f29caf92 Fix race condition in poll_failover_result (#658)
It didn't affect directly neither failover nor switchover, but in some rare cases it was reporting it as a success too early, when the former leader released the lock: `Failed over to "None" instead of "desired-node"`

In addition to that this commit improves logs and status messages by differentiating between failover and switchover.
2018-04-16 17:45:05 +02:00
Alexander KukushkinandGitHub d78790b194 Abort start if attaching to running postgres and cluster not initiazlied (#661)
Patroni can attach itself to an already running PostgreSQL instance. If that is the first instance "seen" in the given cluster, Patroni for that instance will create the initialize key, grab the leader key and, if the instance is running a replica, promote.

Because of this behavior, when a cluster with a master and one or more replicas gets Patroni for each node, it is imperative to start running Patroni on the master node before getting to the replicas.

This commit changes such weird behavior and will abort Patroni start if there is no initialize key in DCS and postgres is running as a replica.

Closes https://github.com/zalando/patroni/issues/655
2018-04-16 17:32:26 +02:00
Kostiantyn NemchenkoandAlexander Kukushkin 3110090154 Minor corrections to the documentation. (#654) 2018-04-16 15:46:46 +02:00
Reinhard NägeleandAlexander Kukushkin 20138af37a Link to official Helm chart (#660)
Changes the link from my outdated fork to the official Helm chart which is now up to date.
2018-04-16 15:45:53 +02:00
Dave CramerandAlexander Kukushkin 38ad394308 Use the word primary in favour of master (#663)
Primary is a better alternative.
2018-04-16 01:29:51 +02:00
Alexander KukushkinandGitHub e375fac273 Treat postgres settings parameter names as case insensitive (#650)
Because they are indeed case insensitive.
Most of the parameters have snake_case_name, but there are three exceptions from this rule: DateStyle, IntervalStyle and TimeZone.
In fact, if you specify timezone = 'some/tzn' it still works, but Patroni wasn't able to find 'timezone' in pg_settings and stripping this parameter out.

We will use CaseInsensitiveDict to keep postgresql.parameters. This change affects only "final" configuration. That means if you put some"duplicates" (work_mem vs WORK_MEM) into patroni yaml or into cluster config, it would be resolved only at the last stage and for example you will be able to see both values if you use `patronictl edit-config`.

Fixes https://github.com/zalando/patroni/issues/649
2018-04-04 14:23:53 +02:00
Alexander KukushkinandGitHub 8c795ff0cf Pass dict object to touch_member instead of json encoded string (#651)
DCS implementation will take care about encoding it.
Fixes https://github.com/zalando/patroni/issues/642
2018-04-04 13:45:44 +02:00
Don SeilerandOleksii Kliukin 140618abd2 Missing a word (#647)
In re Issue #639
2018-04-04 13:40:46 +02:00
Josh BerkusandOleksii Kliukin 3c05e2e984 Added references to the Slack channel in Readme and in contributing.rst. (#653) 2018-04-04 13:39:43 +02:00
bradnicholsonandAlexander Kukushkin ca679a93b8 Make deleting recovery.conf optional. (#638)
pgBackRest's restore command generates the appropriate recovery.conf based
on the parameters you provide to pgBackRest.  When calling pgBackRest's restore command
via Patroni's custom bootstrap, it deletes that recovery.conf.  Specifying the recovery.conf
information in the patroni.yml is less than ideal.  It prevent's leveraging pgBackRests
work to ensure recovery.conf files are properly generated.  It also can lead to transient
config data in the patroni.yml under certain restore cases, such as a PITR restore
of Cluster B to  Cluster A, where the restore_commnand in A needs to reference B.

The parameter is optional.  The default behavior is to delete the recovery.conf.

Fixes https://github.com/zalando/patroni/issues/637
2018-03-09 15:35:29 +01:00
Alexander KukushkinandGitHub f500dbb0ff Release 1.4.3 (#635)
Bump version and update release notes
2018-03-05 10:10:17 +01:00
Andy NewtonandAlexander Kukushkin f748de3b29 Make log level configurable from environment variables (#622)
* `PATRONI_LOGLEVEL` - sets the general logging level
* `PATRONI_REQUESTS_LOGLEVEL` - sets the logging level for all HTTP requests e.g. Kubernetes API calls
2018-03-05 09:50:45 +01:00
Alexander KukushkinandGitHub 3afd26101b Single user mode was waiting for user input and never finish (#634)
Regression was introduced in https://github.com/zalando/patroni/pull/576
2018-03-02 22:22:43 +01:00
Alexander KukushkinandGitHub c04e7a1798 Write bootstrap.pg_hba into a pg_hba.conf after custom bootstrap (#632)
Fixes https://github.com/zalando/patroni/issues/631
2018-02-26 18:48:56 +01:00
Alexander KukushkinandGitHub 89a11fed07 Don't rediscover etcd cluster topology when watch timed out (#630)
but switch to the next node if it is possible.

Fixes https://github.com/zalando/patroni/issues/628
2018-02-26 18:48:30 +01:00
100 changed files with 8210 additions and 3880 deletions
+6
View File
@@ -51,3 +51,9 @@ scm-source.json
docs/build/ docs/build/
docs/source/_static/ docs/source/_static/
docs/source/_templates/ docs/source/_templates/
# Pycharm IDE
.idea/
#VSCode IDE
.vscode/
+8 -4
View File
@@ -1,6 +1,10 @@
sudo: true sudo: true
dist: trusty dist: trusty
language: python language: python
addons:
apt:
packages:
- 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.11 CONSULVERSION=0.7.4
@@ -115,7 +119,7 @@ install:
fi fi
source ~/virtualenv/python${pv}/bin/activate source ~/virtualenv/python${pv}/bin/activate
# explicitly install all needed python modules to cache them # explicitly install all needed python modules to cache them
for p in '-r requirements.txt' 'behave codacy-coverage coverage coveralls flake8 mock pytest-cov pytest setuptools'; do for p in '-r requirements.txt' 'psycopg2-binary behave codacy-coverage coverage coveralls flake8 mock pytest-cov pytest setuptools'; do
pip install $p --upgrade pip install $p --upgrade
done done
fi fi
@@ -131,13 +135,13 @@ script:
if [[ $TEST_SUITE != "behave" ]]; then if [[ $TEST_SUITE != "behave" ]]; then
echo Running unit tests using python${pv} echo Running unit tests using python${pv}
$TEST_SUITE test unbuffer $TEST_SUITE test
$TEST_SUITE flake8 $TEST_SUITE flake8
elif [[ $pv != $EXCLUDE_BEHAVE ]]; then elif [[ $pv != $EXCLUDE_BEHAVE ]]; then
echo Running acceptance tests using python${pv} echo Running acceptance tests using python${pv}
if ! PATH=.:/usr/lib/postgresql/9.6/bin:$PATH $TEST_SUITE; then if ! PATH=.:/usr/lib/postgresql/9.6/bin:$PATH unbuffer $TEST_SUITE; then
# output all log files when tests are failing # output all log files when tests are failing
grep . features/output/*/*postgres?.* grep . features/output/*_failed/*postgres?.*
exit 1 exit 1
fi fi
fi fi
-13
View File
@@ -1,13 +0,0 @@
# for github.com
approvals:
groups:
zalando:
minimum: 2
from:
orgs:
- "zalando"
# team should be valid team id in team service https://teams.auth.zalando.com/api/teams/:id
X-Zalando-Team: "acid"
# type should be one of [code, doc, config, tools, secrets]
# code will be the default value, if X-Zalando-Type is not found in .zappr.yml
X-Zalando-Type: code
+141 -33
View File
@@ -1,48 +1,156 @@
## This Dockerfile is meant to aid in the building and debugging patroni whilst developing on your local machine ## This Dockerfile is meant to aid in the building and debugging patroni whilst developing on your local machine
## It has all the necessary components to play/debug with a single node appliance, running etcd ## It has all the necessary components to play/debug with a single node appliance, running etcd
FROM postgres:9.6 ARG PG_MAJOR=10
MAINTAINER Alexander Kukushkin <[email protected]> ARG COMPRESS=false
ARG PGHOME=/home/postgres
ARG PGDATA=$PGHOME/data
ARG LC_ALL=C.UTF-8
ARG LANG=C.UTF-8
RUN export DEBIAN_FRONTEND=noninteractive \ FROM postgres:$PG_MAJOR as builder
ARG PGHOME
ARG PGDATA
ARG LC_ALL
ARG LANG
ENV ETCDVERSION=2.3.8 CONFDVERSION=0.16.0
RUN set -ex \
&& export DEBIAN_FRONTEND=noninteractive \
&& echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \ && echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \
&& apt-get update -y \ && apt-get update -y \
&& apt-get upgrade -y \ # postgres:10 is based on debian, which has the patroni package. We will install all required dependencies
&& apt-get install -y curl jq haproxy python-psycopg2 python-yaml python-requests python-six python-pysocks \ && apt-cache depends patroni | sed -n -e 's/.*Depends: \(python3-.\+\)$/\1/p' \
python-dateutil python-pip python-setuptools python-prettytable python-wheel python-psutil python locales \ | grep -Ev '^python3-(sphinx|etcd|consul|kazoo|kubernetes)' \
| xargs apt-get install -y vim curl less jq locales haproxy sudo \
## Make sure we have a en_US.UTF-8 locale available python3-etcd python3-kazoo python3-pip busybox \
&& pip3 install dumb-init \
\
# Cleanup all locales but en_US.UTF-8
&& find /usr/share/i18n/charmaps/ -type f ! -name UTF-8.gz -delete \
&& find /usr/share/i18n/locales/ -type f ! -name en_US ! -name en_GB ! -name i18n ! -name iso14651_t1 ! -name iso14651_t1_common ! -name 'translit_*' -delete \
&& echo 'en_US.UTF-8 UTF-8' > /usr/share/i18n/SUPPORTED \
\
# Make sure we have a en_US.UTF-8 locale available
&& localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \ && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \
\
&& pip install 'python-etcd>=0.4.3,<0.5' click tzlocal cdiff \ # haproxy dummy config
&& echo 'global\n stats socket /run/haproxy/admin.sock mode 660 level admin' > /etc/haproxy/haproxy.cfg \
&& mkdir -p /home/postgres \ \
&& chown postgres:postgres /home/postgres \ # vim config
&& echo 'syntax on\nfiletype plugin indent on\nset mouse-=a\nautocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab' > /etc/vim/vimrc.local \
# Clean up \
&& apt-get remove -y python-pip python-setuptools \ # Prepare postgres/patroni/haproxy environment
&& mkdir -p $PGHOME/.config/patroni /patroni /run/haproxy \
&& ln -s ../../postgres0.yml $PGHOME/.config/patroni/patronictl.yaml \
&& ln -s /patronictl.py /usr/local/bin/patronictl \
&& sed -i "s|/var/lib/postgresql.*|$PGHOME:/bin/bash|" /etc/passwd \
&& chown -R postgres:postgres /var/log \
\
# Download etcd
&& curl -sL https://github.com/coreos/etcd/releases/download/v${ETCDVERSION}/etcd-v${ETCDVERSION}-linux-amd64.tar.gz \
| tar xz -C /usr/local/bin --strip=1 --wildcards --no-anchored etcd etcdctl \
\
# Download confd
&& curl -sL https://github.com/kelseyhightower/confd/releases/download/v${CONFDVERSION}/confd-${CONFDVERSION}-linux-amd64 \
> /usr/local/bin/confd && chmod +x /usr/local/bin/confd \
\
# Clean up all useless packages and some files
&& apt-get purge -y --allow-remove-essential python3-pip gzip bzip2 util-linux e2fsprogs \
libmagic1 bsdmainutils login ncurses-bin libmagic-mgc e2fslibs bsdutils \
exim4-config gnupg-agent dirmngr libpython2.7-stdlib libpython2.7-minimal \
&& apt-get autoremove -y \ && apt-get autoremove -y \
&& apt-get clean -y \ && apt-get clean -y \
&& rm -rf /var/lib/apt/lists/* /root/.cache && rm -rf /var/lib/apt/lists/* \
/root/.cache \
/var/cache/debconf/* \
/etc/rc?.d \
/etc/systemd \
/docker-entrypoint* \
/sbin/pam* \
/sbin/swap* \
/sbin/unix* \
/usr/local/bin/gosu \
/usr/sbin/[acgipr]* \
/usr/sbin/*user* \
/usr/share/doc* \
/usr/share/man \
/usr/share/info \
/usr/share/i18n/locales/translit_hangul \
/usr/share/locale/?? \
/usr/share/locale/??_?? \
/usr/share/postgresql/*/man \
/usr/share/postgresql-common/pg_wrapper \
/usr/share/vim/vim80/doc \
/usr/share/vim/vim80/lang \
/usr/share/vim/vim80/tutor \
# /var/lib/dpkg/info/* \
&& find /usr/bin -xtype l -delete \
&& find /var/log -type f -exec truncate --size 0 {} \; \
&& find /usr/lib/python3/dist-packages -name '*test*' | xargs rm -fr \
&& find /lib/x86_64-linux-gnu/security -type f ! -name pam_env.so ! -name pam_permit.so ! -name pam_unix.so -delete
ENV ETCDVERSION 3.2.3 # perform compression if it is necessary
RUN curl -L https://github.com/coreos/etcd/releases/download/v${ETCDVERSION}/etcd-v${ETCDVERSION}-linux-amd64.tar.gz \ ARG COMPRESS
| tar xz -C /usr/local/bin --strip=1 --wildcards --no-anchored etcd etcdctl RUN if [ "$COMPRESS" = "true" ]; then \
set -ex \
# Allow certain sudo commands from postgres
&& echo 'postgres ALL=(ALL) NOPASSWD: /bin/tar xpJf /a.tar.xz -C /, /bin/rm /a.tar.xz, /bin/ln -snf dash /bin/sh' >> /etc/sudoers \
&& ln -snf busybox /bin/sh \
&& files="/bin/sh /usr/bin/sudo /usr/lib/sudo/sudoers.so /lib/x86_64-linux-gnu/security/pam_*.so" \
&& libs="$(ldd $files | awk '{print $3;}' | grep '^/' | sort -u) /lib/x86_64-linux-gnu/ld-linux-x86-64.so.* /lib/x86_64-linux-gnu/libnsl.so.* /lib/x86_64-linux-gnu/libnss_compat.so.*" \
&& (echo /var/run $files $libs | tr ' ' '\n' && realpath $files $libs) | sort -u | sed 's/^\///' > /exclude \
&& find /etc/alternatives -xtype l -delete \
&& save_dirs="usr lib var bin sbin etc/ssl etc/init.d etc/alternatives etc/apt" \
&& XZ_OPT=-e9v tar -X /exclude -cpJf a.tar.xz $save_dirs \
# we call "cat /exclude" to avoid including files from the $save_dirs that are also among
# the exceptions listed in the /exclude, as "uniq -u" eliminates all non-unique lines.
# By calling "cat /exclude" a second time we guarantee that there will be at least two lines
# for each exception and therefore they will be excluded from the output passed to 'rm'.
&& /bin/busybox sh -c "(find $save_dirs -not -type d && cat /exclude /exclude && echo exclude) | sort | uniq -u | xargs /bin/busybox rm" \
&& /bin/busybox --install -s \
&& /bin/busybox sh -c "find $save_dirs -type d -depth -exec rmdir -p {} \; 2> /dev/null"; \
fi
ENV CONFDVERSION 0.11.0 FROM scratch
RUN curl -L https://github.com/kelseyhightower/confd/releases/download/v${CONFDVERSION}/confd-${CONFDVERSION}-linux-amd64 > /usr/local/bin/confd \ COPY --from=builder / /
&& chmod +x /usr/local/bin/confd
ADD patronictl.py patroni.py docker/entrypoint.sh / LABEL maintainer="Alexander Kukushkin <[email protected]>"
ADD patroni /patroni/
ADD extras/confd /etc/confd
RUN ln -s /patronictl.py /usr/local/bin/patronictl
### Setting up a simple script that will serve as an entrypoint ARG PG_MAJOR
RUN mkdir /data/ && touch /pgpass /patroni.yml \ ARG COMPRESS
&& chown postgres:postgres -R /patroni/ /data/ /pgpass /patroni.yml /etc/haproxy /var/run/ /var/lib/ /var/log/ ARG PGHOME
ARG PGDATA
ARG LC_ALL
ARG LANG
EXPOSE 2379 5432 8008 ARG PGBIN=/usr/lib/postgresql/$PG_MAJOR/bin
ENV LC_ALL=$LC_ALL LANG=$LANG EDITOR=/usr/bin/editor
ENV PGDATA=$PGDATA PATH=$PATH:$PGBIN
COPY patroni /patroni/
COPY extras/confd/conf.d/haproxy.toml /etc/confd/conf.d/
COPY extras/confd/templates/haproxy.tmpl /etc/confd/templates/
COPY patroni*.py docker/entrypoint.sh /
COPY postgres?.yml $PGHOME/
WORKDIR $PGHOME
RUN sed -i 's/env python/&3/' /patroni*.py \
# "fix" patroni configs
&& sed -i 's/^\( connect_address:\| - host\)/#&/' postgres?.yml \
&& sed -i 's/^ listen: 127.0.0.1/ listen: 0.0.0.0/' postgres?.yml \
&& sed -i "s|^\( data_dir: \).*|\1$PGDATA|" postgres?.yml \
&& sed -i "s|^#\( bin_dir: \).*|\1$PGBIN|" postgres?.yml \
&& sed -i 's/^ - encoding: UTF8/ - locale: en_US.UTF-8\n&/' postgres?.yml \
&& sed -i 's/^\(scope\|name\|etcd\| host\| authentication\| pg_hba\| parameters\):/#&/' postgres?.yml \
&& sed -i 's/^ \(replication\|superuser\|rewind\|unix_socket_directories\|\(\( \)\{0,1\}\(username\|password\)\)\):/#&/' postgres?.yml \
&& sed -i 's/^ parameters:/ pg_hba:\n - local all all trust\n - host replication all all md5\n - host all all all md5\n&\n max_connections: 100/' postgres?.yml \
&& if [ "$COMPRESS" = "true" ]; then chmod u+s /usr/bin/sudo; fi \
&& chown -R postgres:postgres $PGHOME /run /etc/haproxy
ENV LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
ENTRYPOINT ["/bin/bash", "/entrypoint.sh"]
USER postgres USER postgres
ENTRYPOINT ["/bin/sh", "/entrypoint.sh"]
+34 -1
View File
@@ -29,7 +29,7 @@ For an example of a Docker-based deployment with Patroni, see `Spilo <https://gi
For additional background info, see: For additional background info, see:
* `Elephants on Automatic: HA Clustered PostgreSQL with Helm <https://www.youtube.com/watch?v=CftcVhFMGSY>`_, talk by Josh Berkus and Oleksii Kliukin at KubeCon Berlin 2017 * `Elephants on Automatic: HA Clustered PostgreSQL with Helm <https://www.youtube.com/watch?v=CftcVhFMGSY>`_, talk by Josh Berkus and Oleksii Kliukin at KubeCon Berlin 2017
* `PostgreSQL HA with Kubernetes and Patroni <https://www.youtube.com/watch?v=iruaCgeG7qs>`__, talk by Josh Berkus at KubeCon 2016 (video) * `PostgreSQL HA with Kubernetes and Patroni <https://www.youtube.com/watch?v=iruaCgeG7qs>`__, talk by Josh Berkus at KubeCon 2016 (video)
* `Feb. 2016 Zalando Tech blog post <https://tech.zalando.de/blog/zalandos-patroni-a-template-for-high-availability-postgresql/>`__ * `Feb. 2016 Zalando Tech blog post <https://tech.zalando.de/blog/zalandos-patroni-a-template-for-high-availability-postgresql/>`__
@@ -41,6 +41,12 @@ Patroni is in active development and accepts contributions. See our `Contributin
We report new releases information `here <https://github.com/zalando/patroni/releases>`__. We report new releases information `here <https://github.com/zalando/patroni/releases>`__.
=========
Community
=========
There are two places to connect with the Patroni community: `on github <https://github.com/zalando/patroni>`__, via Issues and PRs, and on channel #patroni in the `PostgreSQL Slack <https://postgres-slack.herokuapp.com/>`__. If you're using Patroni, or just interested, please join us.
=================================== ===================================
Technical Requirements/Installation Technical Requirements/Installation
=================================== ===================================
@@ -53,6 +59,33 @@ To install requirements on a Mac, run the following:
brew install postgresql etcd haproxy libyaml python brew install postgresql etcd haproxy libyaml python
**Psycopg2**
Starting from `psycopg2-2.8 <http://initd.org/psycopg/articles/2019/04/04/psycopg-28-released/>`__ the binary version of psycopg2 will no longer be installed by default. Installing it from the source code requires C compiler and postgres+python dev packages.
Since in the python world it is not possible to specify dependency as ``psycopg2 OR psycopg2-binary`` you will have to decide how to install it.
There are a few options available:
1. Use the package manager from your distro
::
sudo apt-get install python-psycopg2 # install python2 psycopg2 module on Debian/Ubuntu
sudo apt-get install python3-psycopg2 # install python3 psycopg2 module on Debian/Ubuntu
sudo yum install python-psycopg2 # install python2 psycopg2 on RedHat/Fedora/CentOS
2. Install psycopg2 from the binary package
::
pip install psycopg2-binary
3. Install psycopg2 from source
::
pip install psycopg2>=2.5.4
**General installation for pip** **General installation for pip**
Patroni can be installed with pip: Patroni can be installed with pip:
+63 -52
View File
@@ -1,58 +1,69 @@
# docker compose file for running a 3-node PostgreSQL cluster # docker compose file for running a 3-node PostgreSQL cluster
# with etcd as the SIS # with 3-node etcd cluster as the DCS and one haproxy node
version: "2"
patroni_etcd: networks:
container_name: patroni_etcd demo:
image: patroni
command: --etcd
dbnode1: services:
image: patroni etcd1:
hostname: dbnode1 image: patroni
links: networks: [ demo ]
- patroni_etcd:patroni_etcd env_file: docker/etcd.env
volumes: container_name: demo-etcd1
- ./patroni:/patroni hostname: etcd1
env_file: docker/patroni-secrets.env command: etcd -name etcd1 -initial-advertise-peer-urls http://etcd1:2380
environment:
PATRONI_ETCD_HOST: patroni_etcd:2379
PATRONI_NAME: dbnode1
PATRONI_SCOPE: testcluster
dbnode2: etcd2:
image: patroni image: patroni
hostname: dbnode2 networks: [ demo ]
links: env_file: docker/etcd.env
- patroni_etcd:patroni_etcd container_name: demo-etcd2
volumes: hostname: etcd2
- ./patroni:/patroni command: etcd -name etcd2 -initial-advertise-peer-urls http://etcd2:2380
env_file: docker/patroni-secrets.env
environment:
PATRONI_ETCD_HOST: patroni_etcd:2379
PATRONI_NAME: dbnode2
PATRONI_SCOPE: testcluster
dbnode3: etcd3:
image: patroni image: patroni
hostname: dbnode3 networks: [ demo ]
links: env_file: docker/etcd.env
- patroni_etcd:patroni_etcd container_name: demo-etcd3
volumes: hostname: etcd3
- ./patroni:/patroni command: etcd -name etcd3 -initial-advertise-peer-urls http://etcd3:2380
env_file: docker/patroni-secrets.env
environment:
PATRONI_ETCD_HOST: patroni_etcd:2379
PATRONI_NAME: dbnode3
PATRONI_SCOPE: testcluster
haproxy: patroni1:
image: patroni image: patroni
links: networks: [ demo ]
- patroni_etcd:patroni_etcd env_file: docker/patroni.env
ports: hostname: patroni1
- "5000:5000" container_name: demo-patroni1
- "5001:5001" environment:
environment: PATRONI_NAME: patroni1
PATRONI_ETCD_HOST: patroni_etcd:2379
PATRONI_SCOPE: testcluster patroni2:
command: --confd image: patroni
networks: [ demo ]
env_file: docker/patroni.env
hostname: patroni2
container_name: demo-patroni2
environment:
PATRONI_NAME: patroni2
patroni3:
image: patroni
networks: [ demo ]
env_file: docker/patroni.env
hostname: patroni3
container_name: demo-patroni3
environment:
PATRONI_NAME: patroni3
haproxy:
image: patroni
networks: [ demo ]
env_file: docker/patroni.env
hostname: haproxy
container_name: demo-haproxy
ports:
- "5000:5000"
- "5001:5001"
command: haproxy
+103 -33
View File
@@ -1,47 +1,117 @@
# Patroni Dockerfile # Patroni Dockerfile
You can run Patroni in a docker container using this Dockerfile, or by using one of the Docker image at You can run Patroni in a docker container using this Dockerfile
https://registry.opensource.zalan.do/v1/repositories/acid/patroni/tags
This Dockerfile is meant in aiding development of Patroni and quick testing of features. It is not a production-worthy This Dockerfile is meant in aiding development of Patroni and quick testing of features. It is not a production-worthy
Dockerfile Dockerfile
docker build -t patroni .
# Examples # Examples
## Standalone Patroni ## Standalone Patroni
docker run -d registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT docker run -d patroni
## Multiple Patroni's communicating with a standalone etcd inside Docker ## Three-node Patroni cluster with three-node etcd cluster and one haproxy container using docker-compose
Basically what you would do would be:
* Run 1 container which provides etcd
docker run -d <IMAGE> --etcd-only
* Run n containers running Patroni, passing the `--etcd` option to the `docker run` command
docker run -d <IMAGE> --etcd=<IP FROM etcd CONTAINER:PORT>
To automate this you can run the following script:
dev_patroni_cluster.sh [OPTIONS]
Options:
--image IMAGE The Docker image to use for the cluster
--members INT The number of members for the cluster
--name NAME The name of the new cluster
Example session: Example session:
$ ./dev_patroni_cluster.sh --image registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT --members=2 --name=bravo $ docker-compose up -d
The etcd container is 6be871a11cb373406ca5ea1c6b39e1.0-SNAPSHOTfdde9fb1d6177212d6ad0c0d1bd9b563, ip=172.17.1.24 Creating demo-haproxy ...
Started Patroni container 67e611f2eca7c40f9e6e0e24a4a8f2cba7e3e56d22a420e15ab9240a37a9d7a4, ip=172.17.1.25 Creating demo-patroni2 ...
Started Patroni container 47dd12ae635ab83b039f5889e250048b606ed5e48e3650b69e365e7e1d4acbcf, ip=172.17.1.26 Creating demo-patroni1 ...
Creating demo-patroni3 ...
Creating demo-etcd2 ...
Creating demo-etcd1 ...
Creating demo-etcd3 ...
Creating demo-haproxy
Creating demo-patroni2
Creating demo-patroni1
Creating demo-patroni3
Creating demo-etcd1
Creating demo-etcd2
Creating demo-etcd2 ... done
$ docker ps $ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
47dd12ae635a registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT "/bin/bash /entrypoi 10 seconds ago Up 8 seconds 4001/tcp, 5432/tcp, 2380/tcp bravo_OR64g8bx 5b7a90b4cfbf patroni "/bin/sh /entrypoint…" 29 seconds ago Up 27 seconds demo-etcd2
67e611f2eca7 registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT "/bin/bash /entrypoi 11 seconds ago Up 10 seconds 2380/tcp, 4001/tcp, 5432/tcp bravo_si9no8iz e30eea5222f2 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 27 seconds demo-etcd1
6be871a11cb3 registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT "/bin/bash /entrypoi 12 seconds ago Up 10 seconds 4001/tcp, 5432/tcp, 2380/tcp bravo_etcd 83bcf3cb208f patroni "/bin/sh /entrypoint…" 29 seconds ago Up 27 seconds demo-etcd3
922532c56e7d patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds demo-patroni3
14f875e445f3 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds demo-patroni2
110d1073b383 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds demo-patroni1
5af5e6e36028 patroni "/bin/sh /entrypoint…" 29 seconds ago Up 28 seconds 0.0.0.0:5000-5001->5000-5001/tcp demo-haproxy
$ docker logs demo-patroni1
2019-02-20 08:19:32,714 INFO: Failed to import patroni.dcs.consul
2019-02-20 08:19:32,737 INFO: Selected new etcd server http://etcd3:2379
2019-02-20 08:19:35,140 INFO: Lock owner: None; I am patroni1
2019-02-20 08:19:35,174 INFO: trying to bootstrap a new cluster
...
2019-02-20 08:19:39,310 INFO: postmaster pid=37
2019-02-20 08:19:39.314 UTC [37] LOG: listening on IPv4 address "0.0.0.0", port 5432
2019-02-20 08:19:39.321 UTC [37] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2019-02-20 08:19:39.353 UTC [39] LOG: database system was shut down at 2019-02-20 08:19:36 UTC
2019-02-20 08:19:39.354 UTC [40] FATAL: the database system is starting up
localhost:5432 - rejecting connections
2019-02-20 08:19:39.369 UTC [37] LOG: database system is ready to accept connections
localhost:5432 - accepting connections
2019-02-20 08:19:39,383 INFO: establishing a new patroni connection to the postgres cluster
2019-02-20 08:19:39,408 INFO: running post_bootstrap
2019-02-20 08:19:39,432 WARNING: Could not activate Linux watchdog device: "Can't open watchdog device: [Errno 2] No such file or directory: '/dev/watchdog'"
2019-02-20 08:19:39,515 INFO: initialized a new cluster
2019-02-20 08:19:49,424 INFO: Lock owner: patroni1; I am patroni1
2019-02-20 08:19:49,447 INFO: Lock owner: patroni1; I am patroni1
2019-02-20 08:19:49,480 INFO: no action. i am the leader with the lock
2019-02-20 08:19:59,422 INFO: Lock owner: patroni1; I am patroni1
$ docker exec -ti demo-patroni1 bash
postgres@patroni1:~$ patronictl list
+---------+----------+------------+--------+---------+----+-----------+
| Cluster | Member | Host | Role | State | TL | Lag in MB |
+---------+----------+------------+--------+---------+----+-----------+
| demo | patroni1 | 172.22.0.3 | Leader | running | 1 | 0 |
| demo | patroni2 | 172.22.0.7 | | running | 1 | 0 |
| demo | patroni3 | 172.22.0.4 | | running | 1 | 0 |
+---------+----------+------------+--------+---------+----+-----------+
postgres@patroni1:~$ etcdctl ls --recursive --sort -p /service/demo
/service/demo/config
/service/demo/initialize
/service/demo/leader
/service/demo/members/
/service/demo/members/patroni1
/service/demo/members/patroni2
/service/demo/members/patroni3
/service/demo/optime/
/service/demo/optime/leader
postgres@patroni1:~$ etcdctl member list
1bab629f01fa9065: name=etcd3 peerURLs=http://etcd3:2380 clientURLs=http://etcd3:2379 isLeader=false
8ecb6af518d241cc: name=etcd2 peerURLs=http://etcd2:2380 clientURLs=http://etcd2:2379 isLeader=true
b2e169fcb8a34028: name=etcd1 peerURLs=http://etcd1:2380 clientURLs=http://etcd1:2379 isLeader=false
postgres@patroni1:~$ exit
$ psql -h localhost -p 5000 -U postgres -W
Password: postgres
psql (11.2 (Ubuntu 11.2-1.pgdg18.04+1), server 10.7 (Debian 10.7-1.pgdg90+1))
Type "help" for help.
localhost/postgres=# select pg_is_in_recovery();
pg_is_in_recovery
───────────────────
f
(1 row)
localhost/postgres=# \q
$ psql -h localhost -p 5001 -U postgres -W
Password: postgres
psql (11.2 (Ubuntu 11.2-1.pgdg18.04+1), server 10.7 (Debian 10.7-1.pgdg90+1))
Type "help" for help.
localhost/postgres=# select pg_is_in_recovery();
pg_is_in_recovery
───────────────────
t
(1 row)
-104
View File
@@ -1,104 +0,0 @@
#!/bin/bash
DOCKER_IMAGE="registry.opensource.zalan.do/acid/patroni:1.0-SNAPSHOT"
MEMBERS=3
function usage()
{
cat <<__EOF__
Usage: $0
Options:
--image IMAGE The Docker image to use for the cluster
--members INT The number of members for the cluster
--name NAME The name of the new cluster
Examples:
$0 --image ${DOCKER_IMAGE}
$0
$0 --image ${DOCKER_IMAGE} --members=2
__EOF__
}
optspec=":-:"
while getopts "$optspec" optchar; do
case "${optchar}" in
-)
case "${OPTARG}" in
help)
usage
exit 0
;;
name)
PATRONI_SCOPE="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
name=*)
PATRONI_SCOPE="${OPTARG#*=}"
;;
image)
DOCKER_IMAGE="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
image=*)
DOCKER_IMAGE="${OPTARG#*=}"
;;
members)
MEMBERS="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
;;
members=*)
MEMBERS="${OPTARG#*=}"
;;
*)
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
echo "Unknown option --${OPTARG}" >&2
fi
;;
esac;;
*)
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
echo "Non-option argument: '-${OPTARG}'" >&2
usage
exit 1
fi
;;
esac
done
if [ -z ${PATRONI_SCOPE} ]; then
PATRONI_SCOPE=$(cat /dev/urandom | LC_ALL=C tr -dc 'a-z0-9' | head -c 8)
fi
function docker_run()
{
local name=$1
shift
container=$(docker run -d --name=$name $*)
container_ip=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${container})
echo "Started container ${name}, ip=${container_ip}"
}
ETCD_CONTAINER="${PATRONI_SCOPE}_etcd"
docker_run ${ETCD_CONTAINER} ${DOCKER_IMAGE} --etcd
DOCKER_ARGS="--link=${ETCD_CONTAINER}:${ETCD_CONTAINER} -e PATRONI_SCOPE=${PATRONI_SCOPE} -e PATRONI_ETCD_HOST=${ETCD_CONTAINER}:2379"
PATRONI_ENV=$(sed 's/#.*//g' docker/patroni-secrets.env | sed -n 's/^PATRONI_.*$/-e &/p' | tr '\n' ' ')
PATRONI_VOLUME="-v $(dirname $(dirname $(realpath $0)))/patroni:/patroni"
for i in $(seq 1 "${MEMBERS}"); do
container_name=postgres${i}
docker_run "${PATRONI_SCOPE}_${container_name}" \
$PATRONI_VOLUME \
$DOCKER_ARGS \
$PATRONI_ENV \
-e PATRONI_NAME=${container_name} \
${DOCKER_IMAGE}
done
docker_run "${PATRONI_SCOPE}_haproxy" \
-p=5000 -p=5001 \
$DOCKER_ARGS \
${DOCKER_IMAGE} --confd
+45 -100
View File
@@ -1,115 +1,60 @@
#!/bin/bash #!/bin/sh
function usage() if [ -f /a.tar.xz ]; then
{ echo "decompressing image..."
cat <<__EOF__ sudo tar xpJf /a.tar.xz -C / > /dev/null 2>&1
Usage: $0 sudo rm /a.tar.xz
sudo ln -snf dash /bin/sh
fi
Options: readonly PATRONI_SCOPE=${PATRONI_SCOPE:-batman}
PATRONI_NAMESPACE=${PATRONI_NAMESPACE:-/service}
readonly PATRONI_NAMESPACE=${PATRONI_NAMESPACE%/}
readonly DOCKER_IP=$(hostname --ip-address)
--etcd Do not run Patroni, run a standalone etcd case "$1" in
--confd Do not run Patroni, run a standalone confd haproxy)
--zookeeper Do not run Patroni, run a standalone zookeeper haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -D
CONFD="confd -prefix=$PATRONI_NAMESPACE/$PATRONI_SCOPE -interval=10 -backend"
Examples: if [ ! -z "$PATRONI_ZOOKEEPER_HOSTS" ]; then
while ! /usr/share/zookeeper/bin/zkCli.sh -server $PATRONI_ZOOKEEPER_HOSTS ls /; do
$0 --etcd sleep 1
$0 --confd done
$0 --zookeeper exec dumb-init $CONFD zookeeper -node $PATRONI_ZOOKEEPER_HOSTS
$0 else
__EOF__ while ! etcdctl cluster-health 2> /dev/null; do
} sleep 1
done
DOCKER_IP=$(hostname --ip-address) exec dumb-init $CONFD etcd -node $(echo $ETCDCTL_ENDPOINTS | sed 's/,/ -node /g')
PATRONI_SCOPE=${PATRONI_SCOPE:-batman} fi
ETCD_ARGS="--data-dir /tmp/etcd.data -advertise-client-urls=http://${DOCKER_IP}:2379 -listen-client-urls=http://0.0.0.0:2379" ;;
etcd)
optspec=":vh-:" exec "$@" -advertise-client-urls http://$DOCKER_IP:2379
while getopts "$optspec" optchar; do ;;
case "${optchar}" in zookeeper)
-) exec /usr/share/zookeeper/bin/zkServer.sh start-foreground
case "${OPTARG}" in ;;
confd) esac
haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -D
CONFD="confd -prefix=${PATRONI_NAMESPACE:-/service}/$PATRONI_SCOPE -interval=10 -backend"
if [ ! -z ${PATRONI_ZOOKEEPER_HOSTS} ]; then
while ! /usr/share/zookeeper/bin/zkCli.sh -server ${PATRONI_ZOOKEEPER_HOSTS} ls /; do
sleep 1
done
exec $CONFD zookeeper -node ${PATRONI_ZOOKEEPER_HOSTS}
else
while ! curl -s ${PATRONI_ETCD_HOST}/v2/members | jq -r '.members[0].clientURLs[0]' | grep -q http; do
sleep 1
done
exec $CONFD etcd -node $PATRONI_ETCD_HOST
fi
;;
etcd)
exec etcd $ETCD_ARGS
;;
zookeeper)
exec /usr/share/zookeeper/bin/zkServer.sh start-foreground
;;
cheat)
CHEAT=1
;;
help)
usage
exit 0
;;
*)
if [ "$OPTERR" = 1 ] && [ "${optspec:0:1}" != ":" ]; then
echo "Unknown option --${OPTARG}" >&2
fi
;;
esac;;
*)
if [ "$OPTERR" != 1 ] || [ "${optspec:0:1}" = ":" ]; then
echo "Non-option argument: '-${OPTARG}'" >&2
usage
exit 1
fi
;;
esac
done
## We start an etcd ## We start an etcd
if [[ -z ${PATRONI_ETCD_HOST} && -z ${PATRONI_ZOOKEEPER_HOSTS} ]]; then if [ -z "$PATRONI_ETCD_HOSTS" ] && [ -z "$PATRONI_ZOOKEEPER_HOSTS" ]; then
etcd $ETCD_ARGS > /var/log/etcd.log 2> /var/log/etcd.err & export PATRONI_ETCD_URL="http://127.0.0.1:2379"
export PATRONI_ETCD_HOST="127.0.0.1:2379" etcd --data-dir /tmp/etcd.data -advertise-client-urls=$PATRONI_ETCD_URL -listen-client-urls=http://0.0.0.0:2379 > /var/log/etcd.log 2> /var/log/etcd.err &
fi fi
export PATRONI_SCOPE export PATRONI_SCOPE
export PATRONI_NAME="${PATRONI_NAME:-${HOSTNAME}}" export PATRONI_NAMESPACE
export PATRONI_RESTAPI_CONNECT_ADDRESS="${DOCKER_IP}:8008" export PATRONI_NAME="${PATRONI_NAME:-$(hostname)}"
export PATRONI_RESTAPI_CONNECT_ADDRESS="$DOCKER_IP:8008"
export PATRONI_RESTAPI_LISTEN="0.0.0.0:8008" export PATRONI_RESTAPI_LISTEN="0.0.0.0:8008"
export PATRONI_admin_PASSWORD="${PATRONI_admin_PASSWORD:=admin}" export PATRONI_admin_PASSWORD="${PATRONI_admin_PASSWORD:-admin}"
export PATRONI_admin_OPTIONS="${PATRONI_admin_OPTIONS:-createdb, createrole}" export PATRONI_admin_OPTIONS="${PATRONI_admin_OPTIONS:-createdb, createrole}"
export PATRONI_POSTGRESQL_CONNECT_ADDRESS="${DOCKER_IP}:5432" export PATRONI_POSTGRESQL_CONNECT_ADDRESS="$DOCKER_IP:5432"
export PATRONI_POSTGRESQL_LISTEN="0.0.0.0:5432" export PATRONI_POSTGRESQL_LISTEN="0.0.0.0:5432"
export PATRONI_POSTGRESQL_DATA_DIR="data/${PATRONI_SCOPE}" export PATRONI_POSTGRESQL_DATA_DIR="${PATRONI_POSTGRESQL_DATA_DIR:-$PGDATA}"
export PATRONI_REPLICATION_USERNAME="${PATRONI_REPLICATION_USERNAME:-replicator}" export PATRONI_REPLICATION_USERNAME="${PATRONI_REPLICATION_USERNAME:-replicator}"
export PATRONI_REPLICATION_PASSWORD="${PATRONI_REPLICATION_PASSWORD:-abcd}" export PATRONI_REPLICATION_PASSWORD="${PATRONI_REPLICATION_PASSWORD:-replicate}"
export PATRONI_SUPERUSER_USERNAME="${PATRONI_SUPERUSER_USERNAME:-postgres}" export PATRONI_SUPERUSER_USERNAME="${PATRONI_SUPERUSER_USERNAME:-postgres}"
export PATRONI_SUPERUSER_PASSWORD="${PATRONI_SUPERUSER_PASSWORD:-postgres}" export PATRONI_SUPERUSER_PASSWORD="${PATRONI_SUPERUSER_PASSWORD:-postgres}"
export PATRONI_POSTGRESQL_PGPASS="$HOME/.pgpass"
cat > /patroni.yml <<__EOF__ exec python3 /patroni.py postgres0.yml
bootstrap:
dcs:
postgresql:
use_pg_rewind: true
pg_hba:
- host all all 0.0.0.0/0 md5
- host replication replicator ${DOCKER_IP}/16 md5
__EOF__
mkdir -p "$HOME/.config/patroni"
[ -h "$HOME/.config/patroni/patronictl.yaml" ] || ln -s /patroni.yml "$HOME/.config/patroni/patronictl.yaml"
[ -z $CHEAT ] && exec python /patroni.py /patroni.yml
while true; do
sleep 60
done
+5
View File
@@ -0,0 +1,5 @@
ETCD_LISTEN_PEER_URLS=http://0.0.0.0:2380
ETCD_LISTEN_CLIENT_URLS=http://0.0.0.0:2379
ETCD_INITIAL_CLUSTER=etcd1=http://etcd1:2380,etcd2=http://etcd2:2380,etcd3=http://etcd3:2380
ETCD_INITIAL_CLUSTER_STATE=new
ETCD_INITIAL_CLUSTER_TOKEN=tutorial
@@ -1,3 +1,6 @@
PATRONI_SCOPE=demo
PATRONI_ETCD_HOSTS='etcd1:2379','etcd2:2379','etcd3:2379'
PATRONI_RESTAPI_USERNAME=admin PATRONI_RESTAPI_USERNAME=admin
PATRONI_RESTAPI_PASSWORD=admin PATRONI_RESTAPI_PASSWORD=admin
PATRONI_SUPERUSER_USERNAME=postgres PATRONI_SUPERUSER_USERNAME=postgres
@@ -6,3 +9,6 @@ PATRONI_REPLICATION_USERNAME=replicator
PATRONI_REPLICATION_PASSWORD=replicate PATRONI_REPLICATION_PASSWORD=replicate
PATRONI_admin_PASSWORD=admin PATRONI_admin_PASSWORD=admin
PATRONI_admin_OPTIONS=createdb,createrole PATRONI_admin_OPTIONS=createdb,createrole
# for etcdctl
ETCDCTL_ENDPOINTS=http://etcd1:2379,http://etcd2:2379,http://etcd3:2379
+5
View File
@@ -5,6 +5,11 @@ Contributing guidelines
Wanna contribute to Patroni? Yay - here is how! Wanna contribute to Patroni? Yay - here is how!
Chatting
--------
Just want to chat with other Patroni users? Looking for interactive troubleshooting help? Join us on channel #patroni in the `PostgreSQL Slack <https://postgres-slack.herokuapp.com/>`__.
Reporting issues Reporting issues
---------------- ----------------
+28 -8
View File
@@ -11,6 +11,16 @@ Global/Universal
- **PATRONI\_NAME**: name of the node where the current instance of Patroni is running. Must be unique for the cluster. - **PATRONI\_NAME**: name of the node where the current instance of Patroni is running. Must be unique for the cluster.
- **PATRONI\_NAMESPACE**: path within the configuration store where Patroni will keep information about the cluster. Default value: "/service" - **PATRONI\_NAMESPACE**: path within the configuration store where Patroni will keep information about the cluster. Default value: "/service"
- **PATRONI\_SCOPE**: cluster name - **PATRONI\_SCOPE**: cluster name
- **PATRONI\_LOG\_LEVEL**: sets the general logging level. Default value is **INFO** (see `the docs for Python logging <https://docs.python.org/3.6/library/logging.html#levels>`_)
- **PATRONI\_LOG\_FORMAT**: sets the log formatting string. Default value is **%(asctime)s %(levelname)s: %(message)s** (see `the LogRecord attributes <https://docs.python.org/3.6/library/logging.html#logrecord-attributes>`_)
- **PATRONI\_LOG\_DATEFORMAT**: sets the datetime formatting string. (see the `formatTime() documentation <https://docs.python.org/3.6/library/logging.html#logging.Formatter.formatTime>`_)
- **PATRONI\_LOG\_MAX\_QUEUE\_SIZE**: Patroni is using two-step logging. Log records are written into the in-memory queue and there is a separate thread which pulls them from the queue and writes to stderr or file. The maximum size of the internal queue is limited by default by **1000** records, which is enough to keep logs for the past 1h20m.
- **PATRONI\_LOG\_DIR**: Directory to write application logs to. The directory must exist and be writable by the user executing Patroni. If you set this env variable, the application will retain 4 25MB logs by default. You can tune those retention values with `PATRONI_LOG_FILE_NUM` and `PATRONI_LOG_FILE_SIZE` (see below).
- **PATRONI\_LOG\_FILE\_NUM**: The number of application logs to retain.
- **PATRONI\_LOG\_FILE\_SIZE**: Size of patroni.log file (in bytes) that triggers a log rolling.
- **PATRONI\_LOG\_LOGGERS**: Redefine logging level per python module. Example ``PATRONI_LOG_LOGGERS="{patroni.postmaster: WARNING, urllib3: DEBUG}"``
- **PATRONI\_DEBUG\_MODE**: When set to a non-empty value, makes Patroni run in the special debug mode that enables stepping with a debugger through some execution paths within Patroni `
Example ``PATRONI_DEBUG_MODE="on"``
Bootstrap configuration Bootstrap configuration
----------------------- -----------------------
@@ -29,21 +39,29 @@ Consul
- **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
- **PATRONI\_CONSUL\_VERIFY**: (optional) whether to verify the SSL certificate for HTTPS requests - **PATRONI\_CONSUL\_VERIFY**: (optional) whether to verify the SSL certificate for HTTPS requests
- **PATRONI\_CONSUL\_CACERT**: (optional) The ca certificate. If pressent it will enable validation. - **PATRONI\_CONSUL\_CACERT**: (optional) The ca certificate. If present it will enable validation.
- **PATRONI\_CONSUL\_CERT**: (optional) File with the client certificate - **PATRONI\_CONSUL\_CERT**: (optional) File with the client certificate
- **PATRONI\_CONSUL\_KEY**: (optional) File with the client key. Can be empty if the key is part of certificate. - **PATRONI\_CONSUL\_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\_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. 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\_REGISTER\_SERVICE**: (optional) whether or not to register a service with the name defined by the scope parameter and the tag master, replica or standby-leader depending on the node's role. Defaults to **false**
- **PATRONI\_CONSUL\_SERVICE\_CHECK\_INTERVAL**: (optional) how often to perform health check against registered url
Etcd Etcd
---- ----
- **PATRONI\_ETCD\_HOST**: the host:port for the etcd endpoint.
- **PATRONI\_ETCD\_HOSTS**: list of etcd endpoints in format host1:port1,host2:port2,etc...
- **PATRONI\_ETCD\_URL**: url for the etcd, in format: http(s)://(username:password@)host:port
- **PATRONI\_ETCD\_PROXY**: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of **PATRONI\_ETCD\_URL** - **PATRONI\_ETCD\_PROXY**: proxy url for the etcd. If you are connecting to the etcd using proxy, use this parameter instead of **PATRONI\_ETCD\_URL**
- **PATRONI\_ETCD\_URL**: url for the etcd, in format: http(s)://(username:password@)host:port
- **PATRONI\_ETCD\_HOSTS**: list of etcd endpoints in format 'host1:port1','host2:port2',etc...
- **PATRONI\_ETCD\_USE\_PROXIES**: If this parameter is set to true, Patroni will consider **hosts** as a list of proxies and will not perform a topology discovery of etcd cluster but stick to a fixed list of **hosts**.
- **PATRONI\_ETCD\_PROTOCOL**: http or https, if not specified http is used. If the **url** or **proxy** is specified - will take protocol from them.
- **PATRONI\_ETCD\_HOST**: the host:port for the etcd endpoint.
- **PATRONI\_ETCD\_SRV**: Domain to search the SRV record(s) for cluster autodiscovery. - **PATRONI\_ETCD\_SRV**: Domain to search the SRV record(s) for cluster autodiscovery.
- **PATRONI\_ETCD\_CACERT**: The ca certificate. If pressent it will enable validation. - **PATRONI\_ETCD\_USERNAME**: username for etcd authentication.
- **PATRONI\_ETCD\_CERT**: File with the client certificate - **PATRONI\_ETCD\_PASSWORD**: password for etcd authentication.
- **PATRONI\_ETCD\_CACERT**: The ca certificate. If present it will enable validation.
- **PATRONI\_ETCD\_CERT**: File with the client certificate.
- **PATRONI\_ETCD\_KEY**: File with the client key. Can be empty if the key is part of certificate. - **PATRONI\_ETCD\_KEY**: File with the client key. Can be empty if the key is part of certificate.
Exhibitor Exhibitor
@@ -61,7 +79,7 @@ Kubernetes
- **PATRONI\_KUBERNETES\_ROLE\_LABEL**: (optional) name of the label containing Postgres role (`master` or `replica`). Patroni will set this label on the pod it is running in. Default value is `role`. - **PATRONI\_KUBERNETES\_ROLE\_LABEL**: (optional) name of the label containing Postgres role (`master` or `replica`). Patroni will set this label on the pod it is running in. Default value is `role`.
- **PATRONI\_KUBERNETES\_USE\_ENDPOINTS**: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state. - **PATRONI\_KUBERNETES\_USE\_ENDPOINTS**: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state.
- **PATRONI\_KUBERNETES\_POD\_IP**: (optional) IP address of the pod Patroni is running in. This value is required when `PATRONI_KUBERNETES_USE_ENDPOINTS` is enabled and is used to populate the leader endpoint subsets when the pod's PostgreSQL is promoted. - **PATRONI\_KUBERNETES\_POD\_IP**: (optional) IP address of the pod Patroni is running in. This value is required when `PATRONI_KUBERNETES_USE_ENDPOINTS` is enabled and is used to populate the leader endpoint subsets when the pod's PostgreSQL is promoted.
- **PATRONI\_KUBERNETES\_PORTS**: (optional) if the Service object has the name for the port, the same name must appear in the Endpoint object, otherwise service wont work. For example, if your service is defined as ``{Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}``, then you have to set ``PATRONI_KUBERNETES_PORTS='{[{"name": "postgresql", "port": 5432}]}'`` and Patroni will use it for updating subsets of the leader Endpoint. This parameter is used only if `PATRONI_KUBERNETES_USE_ENDPOINTS` is set. - **PATRONI\_KUBERNETES\_PORTS**: (optional) if the Service object has the name for the port, the same name must appear in the Endpoint object, otherwise service won't work. For example, if your service is defined as ``{Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}``, then you have to set ``PATRONI_KUBERNETES_PORTS='{[{"name": "postgresql", "port": 5432}]}'`` and Patroni will use it for updating subsets of the leader Endpoint. This parameter is used only if `PATRONI_KUBERNETES_USE_ENDPOINTS` is set.
PostgreSQL PostgreSQL
---------- ----------
@@ -75,9 +93,11 @@ PostgreSQL
- **PATRONI\_REPLICATION\_PASSWORD**: replication password; the user will be created during initialization. - **PATRONI\_REPLICATION\_PASSWORD**: replication password; the user will be created during initialization.
- **PATRONI\_SUPERUSER\_USERNAME**: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres. Also this user is used by pg_rewind. - **PATRONI\_SUPERUSER\_USERNAME**: name for the superuser, set during initialization (initdb) and later used by Patroni to connect to the postgres. Also this user is used by pg_rewind.
- **PATRONI\_SUPERUSER\_PASSWORD**: password for the superuser, set during initialization (initdb). - **PATRONI\_SUPERUSER\_PASSWORD**: password for the superuser, set during initialization (initdb).
- **PATRONI\_REWIND\_USERNAME**: name for the user for ``pg_rewind``; the user will be created during initialization of postgres 11+ and all necessary `permissions <https://www.postgresql.org/docs/11/app-pgrewind.html#id-1.9.5.8.8>`__ will be granted.
- **PATRONI\_REWIND\_PASSWORD**: password for the user for ``pg_rewind``; the user will be created during initialization.
REST API REST API
-------- --------
- **PATRONI\_RESTAPI\_CONNECT\_ADDRESS**: IP address and port to access the REST API. - **PATRONI\_RESTAPI\_CONNECT\_ADDRESS**: IP address and port to access the REST API.
- **PATRONI\_RESTAPI\_LISTEN**: IP address and port that Patroni will listen to, to provide health-check information for HAProxy. - **PATRONI\_RESTAPI\_LISTEN**: IP address and port that Patroni will listen to, to provide health-check information for HAProxy.
- **PATRONI\_RESTAPI\_USERNAME**: Basic-auth username to protect unsafe REST API endpoints. - **PATRONI\_RESTAPI\_USERNAME**: Basic-auth username to protect unsafe REST API endpoints.
+32 -1
View File
@@ -33,6 +33,35 @@ To install requirements on a Mac, run the following:
brew install postgresql etcd haproxy libyaml python brew install postgresql etcd haproxy libyaml python
.. _psycopg2_install_options:
**Psycopg2**
Starting from `psycopg2-2.8 <http://initd.org/psycopg/articles/2019/04/04/psycopg-28-released/>`__ the binary version of psycopg2 will no longer be installed by default. Installing it from the source code requires C compiler and postgres+python dev packages.
Since in the python world it is not possible to specify dependency as ``psycopg2 OR psycopg2-binary`` you will have to decide how to install it.
There are a few options available:
1. Use the package manager from your distro
::
sudo apt-get install python-psycopg2 # install python2 psycopg2 module on Debian/Ubuntu
sudo apt-get install python3-psycopg2 # install python3 psycopg2 module on Debian/Ubuntu
sudo yum install python-psycopg2 # install python2 psycopg2 on RedHat/Fedora/CentOS
2. Install psycopg2 from the binary package
::
pip install psycopg2-binary
3. Install psycopg2 from source
::
pip install psycopg2>=2.5.4
**General installation for pip** **General installation for pip**
Patroni can be installed with pip: Patroni can be installed with pip:
@@ -62,10 +91,12 @@ For example, the command in order to install Patroni together with dependencies
pip install patroni[etcd,aws] pip install patroni[etcd,aws]
Note that external tools to call in the replica creation or custom bootstap scripts (i.e. WAL-E) should be installed Note that external tools to call in the replica creation or custom bootstrap scripts (i.e. WAL-E) should be installed
independently of Patroni. independently of Patroni.
.. _running_configuring:
Running and Configuring Running and Configuring
----------------------- -----------------------
+77 -26
View File
@@ -10,6 +10,21 @@ Global/Universal
- **namespace**: path within the configuration store where Patroni will keep information about the cluster. Default value: "/service" - **namespace**: path within the configuration store where Patroni will keep information about the cluster. Default value: "/service"
- **scope**: cluster name - **scope**: cluster name
Log
---
- **level**: sets the general logging level. Default value is **INFO** (see `the docs for Python logging <https://docs.python.org/3.6/library/logging.html#levels>`_)
- **format**: sets the log formatting string. Default value is **%(asctime)s %(levelname)s: %(message)s** (see `the LogRecord attributes <https://docs.python.org/3.6/library/logging.html#logrecord-attributes>`_)
- **dateformat**: sets the datetime formatting string. (see the `formatTime() documentation <https://docs.python.org/3.6/library/logging.html#logging.Formatter.formatTime>`_)
- **max\_queue\_size**: Patroni is using two-step logging. Log records are written into the in-memory queue and there is a separate thread which pulls them from the queue and writes to stderr or file. The maximum size of the internal queue is limited by default by **1000** records, which is enough to keep logs for the past 1h20m.
- **dir**: Directory to write application logs to. The directory must exist and be writable by the user executing Patroni. If you set this value, the application will retain 4 25MB logs by default. You can tune those retention values with `file_num` and `file_size` (see below).
- **file\_num**: The number of application logs to retain.
- **file\_size**: Size of patroni.log file (in bytes) that triggers a log rolling.
- **loggers**: This section allows redefining logging level per python module
- **patroni.postmaster: WARNING**
- **urllib3: DEBUG**
.. _bootstrap_settings:
Bootstrap configuration Bootstrap configuration
----------------------- -----------------------
- **dcs**: This section will be written into `/<namespace>/<scope>/config` of a given configuration store after initializing of new cluster. This is the global configuration for the cluster. If you want to change some parameters for all cluster nodes - just do it in DCS (or via Patroni API) and all nodes will apply this configuration. - **dcs**: This section will be written into `/<namespace>/<scope>/config` of a given configuration store after initializing of new cluster. This is the global configuration for the cluster. If you want to change some parameters for all cluster nodes - just do it in DCS (or via Patroni API) and all nodes will apply this configuration.
@@ -18,13 +33,27 @@ Bootstrap configuration
- **retry\_timeout**: timeout for DCS and PostgreSQL operation retries. 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. 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.
- **master\_start\_timeout**: the amount of time a master is allowed to recover from failures before failover is triggered. Default is 300 seconds. When set to 0 failover is done immediately after a crash is detected if possible. When using asynchronous replication a failover can cause lost transactions. Best worst case failover time for master failure is: loop\_wait + master\_start\_timeout + loop\_wait, unless master\_start\_timeout is zero, in which case it's just loop\_wait. Set the value according to your durability/availability tradeoff. - **master\_start\_timeout**: the amount of time a master is allowed to recover from failures before failover is triggered. Default is 300 seconds. When set to 0 failover is done immediately after a crash is detected if possible. When using asynchronous replication a failover can cause lost transactions. Best worst case failover time for master failure is: loop\_wait + master\_start\_timeout + loop\_wait, unless master\_start\_timeout is zero, in which case it's just loop\_wait. Set the value according to your durability/availability tradeoff.
- **synchronous\_mode**: turns on synchronous replication mode. In this mode a replica will be chosen as synchronous and only the latest leader and synchronous replica are able to participate in leader election. Synchronous mode makes sure that succesfully committed transactions will not be lost at failover, at the cost of losing availability for writes when Patroni cannot ensure transaction durability. See `replication modes documentation <https://github.com/zalando/patroni/blob/master/docs/replication_modes.rst>`__ for details. - **synchronous\_mode**: turns on synchronous replication mode. In this mode a replica will be chosen as synchronous and only the latest leader and synchronous replica are able to participate in leader election. Synchronous mode makes sure that successfully committed transactions will not be lost at failover, at the cost of losing availability for writes when Patroni cannot ensure transaction durability. See :ref:`replication modes documentation <replication_modes>` for details.
- **synchronous\_mode\_strict**: prevents disabling synchronous replication if no synchronous replicas are available, blocking all client writes to the master. See :ref:`replication modes documentation <replication_modes>` for details.
- **postgresql**: - **postgresql**:
- **use\_pg\_rewind**:whether or not to use pg_rewind - **use\_pg\_rewind**: whether or not to use pg_rewind
- **use\_slots**: whether or not to use replication_slots. Must be False for PostgreSQL 9.3. You should comment out max_replication_slots before it becomes ineligible for leader status. - **use\_slots**: whether or not to use replication_slots. Must be False for PostgreSQL 9.3. You should comment out max_replication_slots before it becomes ineligible for leader status.
- **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower. - **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower.
- **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work. - **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work.
- **method**: custom script to use for bootstrpapping this cluster. - **standby\_cluster**: if this section is defined, we want to bootstrap a standby cluster.
- **host**: an address of remote master
- **port**: a port of remote master
- **primary\_slot\_name**: which slot on the remote master to use for replication. This parameter is optional, the default value is derived from the instance name (see function `slot_name_from_member_name`).
- **create\_replica\_methods**: an ordered list of methods that can be used to bootstrap standby leader from the remote master, can be different from the list defined in :ref:`postgresql_settings`
- **restore\_command**: command to restore WAL records from the remote master to standby leader, can be different from the list defined in :ref:`postgresql_settings`
- **archive\_cleanup\_command**: cleanup command for standby leader
- **recovery\_min\_apply\_delay**: how long to wait before actually apply WAL records on a standby leader
- **slots**: define permanent replication slots. These slots will be preserved during switchover/failover. Patroni will try to create slots before opening connections to the cluster.
- **my_slot_name**: the name of replication slot. 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.
- **type**: slot type. Could be ``physical`` or ``logical``. If the slot is logical, you have to additionally define ``database`` and ``plugin``.
- **database**: the database name where logical slots should be created.
- **plugin**: the plugin name for the logical slot.
- **method**: custom script to use for bootstrapping this cluster.
See :ref:`custom bootstrap methods documentation <custom_bootstrap>` for details. See :ref:`custom bootstrap methods documentation <custom_bootstrap>` for details.
When ``initdb`` is specified revert to the default ``initdb`` command. ``initdb`` is also triggered when no ``method`` When ``initdb`` is specified revert to the default ``initdb`` command. ``initdb`` is also triggered when no ``method``
parameter is present in the configuration file. parameter is present in the configuration file.
@@ -35,7 +64,7 @@ Bootstrap configuration
- **pg\_hba**: list of lines that you should add to pg\_hba.conf. - **pg\_hba**: list of lines that you should add to pg\_hba.conf.
- **- host all all 0.0.0.0/0 md5**. - **- host all all 0.0.0.0/0 md5**.
- **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication. - **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication.
- **users**: Some additional users users which needs to be created after initializing new cluster - **users**: Some additional users which need to be created after initializing new cluster
- **admin**: the name of user - **admin**: the name of user
- **password: zalando**: - **password: zalando**:
- **options**: list of options for CREATE USER statement - **options**: list of options for CREATE USER statement
@@ -54,12 +83,15 @@ Most of the parameters are optional, but you have to specify one of the **host**
- **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 pressent 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/>`__)
- **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. 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
- **register\_service**: (optional) whether or not to register a service with the name defined by the scope parameter and the tag master, replica or standby-leader depending on the node's role. Defaults to **false**
- **service\_check\_interval**: (optional) how often to perform health check against registered url
Etcd Etcd
---- ----
@@ -67,14 +99,15 @@ 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.
- **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.
- **password**: (optional) password for etcd authentication. - **password**: (optional) password for etcd authentication.
- **cacert**: (optional) The ca certificate. If pressent 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**.
Exhibitor Exhibitor
@@ -93,7 +126,7 @@ Kubernetes
- **role\_label**: (optional) name of the label containing role (master or replica). Patroni will set this label on the pod it runs in. Default value is ``role``. - **role\_label**: (optional) name of the label containing role (master or replica). Patroni will set this label on the pod it runs in. Default value is ``role``.
- **use\_endpoints**: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state. - **use\_endpoints**: (optional) if set to true, Patroni will use Endpoints instead of ConfigMaps to run leader elections and keep cluster state.
- **pod\_ip**: (optional) IP address of the pod Patroni is running in. This value is required when `use_endpoints` is enabled and is used to populate the leader endpoint subsets when the pod's PostgreSQL is promoted. - **pod\_ip**: (optional) IP address of the pod Patroni is running in. This value is required when `use_endpoints` is enabled and is used to populate the leader endpoint subsets when the pod's PostgreSQL is promoted.
- **ports**: (optional) if the Service object has the name for the port, the same name must appear in the Endpoint object, otherwise service wont work. For example, if your service is defined as ``{Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}``, then you have to set ``kubernetes.ports: {[{"name": "postgresql", "port": 5432}]}`` and Patroni will use it for updating subsets of the leader Endpoint. This parameter is used only if `kubernetes.use_endpoints` is set. - **ports**: (optional) if the Service object has the name for the port, the same name must appear in the Endpoint object, otherwise service won't work. For example, if your service is defined as ``{Kind: Service, spec: {ports: [{name: postgresql, port: 5432, targetPort: 5432}]}}``, then you have to set ``kubernetes.ports: {[{"name": "postgresql", "port": 5432}]}`` and Patroni will use it for updating subsets of the leader Endpoint. This parameter is used only if `kubernetes.use_endpoints` is set.
.. _postgresql_settings: .. _postgresql_settings:
@@ -106,37 +139,46 @@ PostgreSQL
- **replication**: - **replication**:
- **username**: replication username; the user will be created during initialization. Replicas will use this user to access master via streaming replication - **username**: replication username; the user will be created during initialization. Replicas will use this user to access master via streaming replication
- **password**: replication password; the user will be created during initialization. - **password**: replication password; the user will be created during initialization.
- **rewind**:
- **username**: name for the user for ``pg_rewind``; the user will be created during initialization of postgres 11+ and all necessary `permissions <https://www.postgresql.org/docs/11/app-pgrewind.html#id-1.9.5.8.8>`__ will be granted.
- **password**: password for the user for ``pg_rewind``; the user will be created during initialization.
- **callbacks**: callback scripts to run on certain actions. Patroni will pass the action, role and cluster name. (See scripts/aws.py as an example of how to write them.) - **callbacks**: callback scripts to run on certain actions. Patroni will pass the action, role and cluster name. (See scripts/aws.py as an example of how to write them.)
- **on\_reload**: run this script when configuration reload is triggered. - **on\_reload**: run this script when configuration reload is triggered.
- **on\_restart**: run this script when the cluster restarts. - **on\_restart**: run this script when the postgres restarts (without changing role).
- **on\_role\_change**: run this script when the cluster is being promoted or demoted. - **on\_role\_change**: run this script when the postgres is being promoted or demoted.
- **on\_start**: run this script when the cluster starts. - **on\_start**: run this script when the postgres starts.
- **on\_stop**: run this script when the cluster stops. - **on\_stop**: run this script when the postgres stops.
- **connect\_address**: IP address + port through which Postgres is accessible from other nodes and applications. - **connect\_address**: IP address + port through which Postgres is accessible from other nodes and applications.
- **create\_replica\_method**: an ordered list of the create methods for turning a Patroni node into a new replica. - **create\_replica\_methods**: an ordered list of the create methods for turning a Patroni node into a new replica.
"basebackup" is the default method; other methods are assumed to refer to scripts, each of which is configured as its "basebackup" is the default method; other methods are assumed to refer to scripts, each of which is configured as its
own config item. See :ref:`custom replica creation methods documentation <custom_replica_creation>` for further explanation. own config item. See :ref:`custom replica creation methods documentation <custom_replica_creation>` for further explanation.
- **data\_dir**: The location of the Postgres data directory, either existing or to be initialized by Patroni. - **data\_dir**: The location of the Postgres data directory, either :ref:`existing <existing_data>` or to be initialized by Patroni.
- **config\_dir**: The location of the Postgres configuration directory, defaults to the data directory. Must be writable by Patroni. - **config\_dir**: The location of the Postgres configuration directory, defaults to the data directory. Must be writable by Patroni.
- **bin\_dir**: Path to PostgreSQL binaries. (pg_ctl, pg_rewind, pg_basebackup, postgres) The default value is an empty string meaning that PATH environment variable will be used to find the executables. - **bin\_dir**: Path to PostgreSQL binaries (pg_ctl, pg_rewind, pg_basebackup, postgres). The default value is an empty string meaning that PATH environment variable will be used to find the executables.
- **listen**: IP address + port that Postgres listens to; must be accessible from other nodes in the cluster, if you're using streaming replication. Multiple comma-separated addresses are permitted, as long as the port component is appended after to the last one with a colon, i.e. ``listen: 127.0.0.1,127.0.0.2:5432``. Patroni will use the first address from this list to establish local connections to the PostgreSQL node. - **listen**: IP address + port that Postgres listens to; must be accessible from other nodes in the cluster, if you're using streaming replication. Multiple comma-separated addresses are permitted, as long as the port component is appended after to the last one with a colon, i.e. ``listen: 127.0.0.1,127.0.0.2:5432``. Patroni will use the first address from this list to establish local connections to the PostgreSQL node.
- **use\_unix\_socket**: specifies that Patroni should prefer to use unix sockets to connect to the cluster. Default value is ``false``. If ``unix_socket_directories`` is definded, Patroni will use first suitable value from it to connect to the cluster and fallback to tcp if nothing is suitable. If ``unix_socket_directories`` is not specified in ``postgresql.parameters``, Patroni will assume that default value should be used and omit ``host`` from connection parameters. - **use\_unix\_socket**: specifies that Patroni should prefer to use unix sockets to connect to the cluster. Default value is ``false``. If ``unix_socket_directories`` is defined, Patroni will use the first suitable value from it to connect to the cluster and fallback to tcp if nothing is suitable. If ``unix_socket_directories`` is not specified in ``postgresql.parameters``, Patroni will assume that the default value should be used and omit ``host`` from the connection parameters.
- **pgpass**: path to the `.pgpass <https://www.postgresql.org/docs/current/static/libpq-pgpass.html>`__ password file. Patroni creates this file before executing pg\_basebackup, the post_init script and under some other circumstances. The location must be writable by Patroni. - **pgpass**: path to the `.pgpass <https://www.postgresql.org/docs/current/static/libpq-pgpass.html>`__ password file. Patroni creates this file before executing pg\_basebackup, the post_init script and under some other circumstances. The location must be writable by Patroni.
- **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower. - **recovery\_conf**: additional configuration settings written to recovery.conf when configuring follower.
- **custom\_conf** : path to an optional custom ``postgresql.conf`` file, that will be used in place of ``postgresql.base.conf``. The file must exist on all cluster nodes, be readable by PostgreSQL and will be included from its location on the real ``postgresql.conf``. Note that Patroni will not monitor this file for changes, nor backup it. However, its settings can still be overriden by Patroni's own configuration facilities - see `dynamic configuration <https://github.com/zalando/patroni/blob/master/docs/dynamic_configuration.rst>`__ for details. - **custom\_conf** : path to an optional custom ``postgresql.conf`` file, that will be used in place of ``postgresql.base.conf``. The file must exist on all cluster nodes, be readable by PostgreSQL and will be included from its location on the real ``postgresql.conf``. Note that Patroni will not monitor this file for changes, nor backup it. However, its settings can still be overridden by Patroni's own configuration facilities - see :ref:`dynamic configuration <dynamic_configuration>` for details.
- **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work. - **parameters**: list of configuration settings for Postgres. Many of these are required for replication to work.
- **pg\_hba**: list of lines that Patroni will use to generate ``pg_hba.conf``. This parameter has higher priority than ``bootstrap.pg_hba``. Together with :ref:`dynamic configuration <dynamic_configuration>` it simplifies management of ``pg_hba.conf``. - **pg\_hba**: list of lines that Patroni will use to generate ``pg_hba.conf``. This parameter has higher priority than ``bootstrap.pg_hba``. Together with :ref:`dynamic configuration <dynamic_configuration>` it simplifies management of ``pg_hba.conf``.
- **- host all all 0.0.0.0/0 md5**. - **- host all all 0.0.0.0/0 md5**.
- **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication. - **- host replication replicator 127.0.0.1/32 md5**: A line like this is required for replication.
- **pg\_ident**: list of lines that Patroni will use to generate ``pg_ident.conf``. Together with :ref:`dynamic configuration <dynamic_configuration>` it simplifies management of ``pg_ident.conf``.
- **- mapname1 systemname1 pguser1**.
- **- mapname1 systemname2 pguser2**.
- **pg\_ctl\_timeout**: How long should pg_ctl wait when doing ``start``, ``stop`` or ``restart``. Default value is 60 seconds. - **pg\_ctl\_timeout**: How long should pg_ctl wait when doing ``start``, ``stop`` or ``restart``. Default value is 60 seconds.
- **use\_pg\_rewind**: try to use pg\_rewind on the former leader when it joins cluster as a replica. - **use\_pg\_rewind**: try to use pg\_rewind on the former leader when it joins cluster as a replica.
- **remove\_data\_directory\_on\_rewind\_failure**: If this option is enabled, Patroni will remove postgres data directory and recreate replica. Otherwise it will try to follow the new leader. Default value is **false**. - **remove\_data\_directory\_on\_rewind\_failure**: If this option is enabled, Patroni will remove the PostgreSQL data directory and recreate the replica. Otherwise it will try to follow the new leader. Default value is **false**.
- **replica\_method** for each create_replica_method other than basebackup, you would add a configuration section of the same name. At a minimum, this should include "command" with a full path to the actual script to be executed. Other configuration parameters will be passed along to the script in the form "parameter=value". - **remove\_data\_directory\_on\_diverged\_timelines**: Patroni will remove the PostgreSQL data directory and recreate the replica if it notices that timelines are diverging and the former master can not start streaming from the new master. This option is useful when ``pg_rewind`` can not be used. Default value is **false**.
- **replica\_method**: for each create_replica_methods other than basebackup, you would add a configuration section of the same name. At a minimum, this should include "command" with a full path to the actual script to be executed. Other configuration parameters will be passed along to the script in the form "parameter=value".
REST API REST API
-------- --------
- **connect\_address**: IP address and port to access the REST API. - **connect\_address**: IP address (or hostname) and port, to access the Patroni's REST API. All the members of the cluster must be able to connect to this address, so unless the Patroni setup is intended for a demo inside the localhost, this address must be a non "localhost" or loopback addres (ie: "localhost" or "127.0.0.1"). It can serve as a endpoint for HTTP health checks (read below about the "listen" REST API parameter), and also for user queries (either directly or via the REST API), as well as for the health checks done by the cluster members during leader elections (for example, to determine whether the master is still running, or if there is a node which has a WAL position that is ahead of the one doing the query; etc.) The connect_address is put in the member key in DCS, making it possible to translate the member name into the address to connect to its REST API.
- **listen**: IP address and port that Patroni will listen to, to provide health-check information for HAProxy.
- **listen**: IP address (or hostname) and port that Patroni will listen to for the REST API - to provide also the same health checks and cluster messaging between the participating nodes, as described above. to provide health-check information for HAProxy (or any other load balancer capable of doing a HTTP "OPTION" or "GET" checks).
- **Optional**: - **Optional**:
- **authentication**: - **authentication**:
- **username**: Basic-auth username to protect unsafe REST API endpoints. - **username**: Basic-auth username to protect unsafe REST API endpoints.
@@ -145,12 +187,21 @@ REST API
- **certfile**: Specifies the file with the certificate in the PEM format. If the certfile is not specified or is left empty, the API server will work without SSL. - **certfile**: Specifies the file with the certificate in the PEM format. If the certfile is not specified or is left empty, the API server will work without SSL.
- **keyfile**: Specifies the file with the secret key in the PEM format. - **keyfile**: Specifies the file with the secret key in the PEM format.
.. _patronictl_settings:
CTL
---
- **Optional**:
- **insecure**: Allow connections to REST API without verifying SSL certs.
- **cacert**: Specifices the file with the CA_BUNDLE file or directory with certificates of trusted CAs to use while verifying REST API SSL certs.
- **certfile**: Specifies the file with the certificate in the PEM format to use while verifying REST API SSL certs. If not provided patronictl will use the value provided for REST API "certfile" parameter.
ZooKeeper ZooKeeper
---------- ----------
- **hosts**: list of ZooKeeper cluster members in format: ['host1:port1', 'host2:port2', 'etc...']. - **hosts**: list of ZooKeeper cluster members in format: ['host1:port1', 'host2:port2', 'etc...'].
Watchdog Watchdog
-------- --------
- **mode**: ``off``, ``automatic`` or ``required``. When ``off`` watchdog is disabled. When ``automatic`` watchdog will be used if available, but ignored if it is not. When ``required`` the node will not become a leader unless watchdog can be succesfully enabled. - **mode**: ``off``, ``automatic`` or ``required``. When ``off`` watchdog is disabled. When ``automatic`` watchdog will be used if available, but ignored if it is not. When ``required`` the node will not become a leader unless watchdog can be successfully enabled.
- **device**: Path to watchdog device. Defaults to ``/dev/watchdog``. - **device**: Path to watchdog device. Defaults to ``/dev/watchdog``.
- **safety_margin**: Number of seconds of safety margin between watchdog triggering and leader key expiration. - **safety_margin**: Number of seconds of safety margin between watchdog triggering and leader key expiration.
+4 -3
View File
@@ -16,9 +16,9 @@ Patroni configuration is stored in the DCS (Distributed Configuration Store). Th
These options are defined in the configuration file and take precedence over dynamic configuration. These options are defined in the configuration file and take precedence over dynamic configuration.
patroni.yml could be changed and reload in runtime (without restart of Patroni) by sending SIGHUP to the Patroni process or by performing ``POST /reload`` REST-API request. patroni.yml could be changed and reload in runtime (without restart of Patroni) by sending SIGHUP to the Patroni process or by performing ``POST /reload`` REST-API request.
- Environment :ref:`configuration <environment>` . - Environment :ref:`configuration <environment>`.
It is possible to set/override some of the "Local" configuration parameters with environment variables. It is possible to set/override some of the "Local" configuration parameters with environment variables.
Environment configuration is very useful when you are running in a dynamic environment and you don't know some of the parameters in advance (for example it's not possible to know you external IP address when you are running inside ``docker``). Environment configuration is very useful when you are running in a dynamic environment and you don't know some of the parameters in advance (for example it's not possible to know your external IP address when you are running inside ``docker``).
Some of the PostgreSQL parameters must hold the same values on the master and the replicas. For those, values set either in the local patroni configuration files or via the environment variables take no effect. To alter or set their values one must change the shared configuration in the DCS. Below is the actual list of such parameters together with the default values: Some of the PostgreSQL parameters must hold the same values on the master and the replicas. For those, values set either in the local patroni configuration files or via the environment variables take no effect. To alter or set their values one must change the shared configuration in the DCS. Below is the actual list of such parameters together with the default values:
@@ -42,7 +42,7 @@ There are some other Postgres parameters controlled by Patroni:
- listen_addresses - is set either from ``postgresql.listen`` or from ``PATRONI_POSTGRESQL_LISTEN`` environment variable - listen_addresses - is set either from ``postgresql.listen`` or from ``PATRONI_POSTGRESQL_LISTEN`` environment variable
- port - is set either from ``postgresql.listen`` or from ``PATRONI_POSTGRESQL_LISTEN`` environment variable - port - is set either from ``postgresql.listen`` or from ``PATRONI_POSTGRESQL_LISTEN`` environment variable
- cluster_name - is set either from ``scope`` or from ``PATRRONI_SCOPE`` environment variable - cluster_name - is set either from ``scope`` or from ``PATRONI_SCOPE`` environment variable
- hot_standby: on - hot_standby: on
To be on the safe side parameters from the above lists are not written into ``postgresql.conf``, but passed as a list of arguments to the ``pg_ctl start`` which gives them the highest precedence, even above `ALTER SYSTEM <https://www.postgresql.org/docs/current/static/sql-altersystem.html>`__ To be on the safe side parameters from the above lists are not written into ``postgresql.conf``, but passed as a list of arguments to the ``pg_ctl start`` which gives them the highest precedence, even above `ALTER SYSTEM <https://www.postgresql.org/docs/current/static/sql-altersystem.html>`__
@@ -76,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
- check_timeline: false
- postgresql.use_slots: true - postgresql.use_slots: true
Upon changing these options, Patroni will read the relevant section of the configuration stored in DCS and change its Upon changing these options, Patroni will read the relevant section of the configuration stored in DCS and change its
+36
View File
@@ -0,0 +1,36 @@
.. _existing_data:
Convert a Standalone to a Patroni Cluster
=========================================
This section describes the process for converting a standalone PostgreSQL instance into a Patroni cluster.
To deploy a Patroni cluster without using a pre-existing PostgreSQL instance, see :ref:`Running and Configuring <running_configuring>` instead.
Procedure
---------
A Patroni cluster can be started with a data directory from a single-node PostgreSQL database. This is achieved by following closely these steps:
1. Manually start PostgreSQL daemon
2. Create Patroni superuser and replication users as defined in the :ref:`authentication <postgresql_settings>` section of the Patroni configuration. If this user is created in SQL, the following queries achieve this:
.. code-block:: sql
CREATE USER $PATRONI_SUPERUSER_USERNAME WITH SUPERUSER ENCRYPTED PASSWORD '$PATRONI_SUPERUSER_PASSWORD';
CREATE USER $PATRONI_REPLICATION_USERNAME WITH REPLICATION ENCRYPTED PASSWORD '$PATRONI_REPLICATION_PASSWORD';
3. Start Patroni (e.g. ``patroni /etc/patroni/patroni.yml``). It automatically detects that PostgreSQL daemon is already running but its configuration might be out-of-date.
4. Ask Patroni to restart the node with ``patronictl restart cluster-name node-name``. This step is only required if PostgreSQL configuration is out-of-date.
FAQ
---
- During Patroni startup, Patroni complains that it cannot bind to the PostgreSQL port.
You need to verify ``listen_addresses`` and ``port`` in ``postgresql.conf`` and ``postgresql.listen`` in ``patroni.yml``. Don't forget that ``pg_hba.conf`` should allow such access.
- After asking Patroni to restart the node, PostgreSQL displays the error message ``could not open configuration file "/etc/postgresql/10/main/pg_hba.conf": No such file or directory``
It can mean various things depending on how you manage PostgreSQL configuration. If you specified `postgresql.config_dir`, Patroni generates the ``pg_hba.conf`` based on the settings in the :ref:`bootstrap <bootstrap_settings>` section only when it bootstraps a new cluster. In this scenario the ``PGDATA`` was not empty, therefore no bootstrap happened. This file must exist beforehand.
+1 -1
View File
@@ -45,7 +45,7 @@ Examples
- You can find the full-featured Docker image that can use Persistent Volumes in the - You can find the full-featured Docker image that can use Persistent Volumes in the
`Spilo Project <https://github.com/zalando/spilo>`_. `Spilo Project <https://github.com/zalando/spilo>`_.
- There is also a `Helm chart <https://github.com/unguiculus/charts/tree/feature/patroni/incubator/patroni>`_ - There is also a `Helm chart <https://github.com/kubernetes/charts/tree/master/incubator/patroni>`_
to deploy the Spilo image configured with Patroni running using Kubernetes. to deploy the Spilo image configured with Patroni running using Kubernetes.
- In order to run your database clusters at scale using Patroni and Spilo, take a look at the - In order to run your database clusters at scale using Patroni and Spilo, take a look at the
+1 -1
View File
@@ -25,7 +25,7 @@ When Patroni runs in a paused mode, it does not change the state of PostgreSQL,
- If there is no leader lock in the cluster, the running master acquires the lock. If there is more than one master node, then the first master to acquire the lock wins. If there are no masters altogether, Patroni does not try to promote any replicas. There is an exception in this rule: if there is no leader lock because the old master has demoted itself due to the manual promotion, then only the candidate node mentioned in the promotion request may take the leader lock. When the new leader lock is granted (i.e. after promoting a replica manually), Patroni makes sure the replicas that were streaming from the previous leader will switch to the new one. - If there is no leader lock in the cluster, the running master acquires the lock. If there is more than one master node, then the first master to acquire the lock wins. If there are no masters altogether, Patroni does not try to promote any replicas. There is an exception in this rule: if there is no leader lock because the old master has demoted itself due to the manual promotion, then only the candidate node mentioned in the promotion request may take the leader lock. When the new leader lock is granted (i.e. after promoting a replica manually), Patroni makes sure the replicas that were streaming from the previous leader will switch to the new one.
- When Postgres is stopped, Patroni does not try to start it. When Patroni is stopped, it does not to stop Postgres instance it is managing. - When Postgres is stopped, Patroni does not try to start it. When Patroni is stopped, it does not try to stop the Postgres instance it is managing.
User guide User guide
---------- ----------
+531 -7
View File
@@ -3,6 +3,530 @@
Release notes Release notes
============= =============
Version 1.6.0
-------------
This version adds compatibility with PostgreSQL 12, makes is possible to run pg_rewind without superuser on PostgreSQL 11 and newer, and enables IPv6 support.
**New features**
- Psycopg2 was removed from requirements and must be installed independently (Alexander Kukushkin)
Starting from 2.8.0 ``psycopg2`` was split into two different packages, ``psycopg2``, and ``psycopg2-binary``, which could be installed at the same time into the same place on the filesystem. In order to decrease dependency hell problem, we let a user choose how to install it. There are a few options available, please consult the :ref:`documentation <psycopg2_install_options>`.
- Compatibility with PostgreSQL 12 (Alexander Kukushkin)
Starting from PostgreSQL 12 there is no ``recovery.conf`` anymore and all former recovery parameters are converted into `GUC <https://www.enterprisedb.com/blog/what-is-a-guc-variable>`_. In order to protect from ``ALTER SYSTEM SET primary_conninfo`` or similar, Patroni will parse ``postgresql.auto.conf`` and remove all standby and recovery parameters from there. Patroni config remains backward compatible. For example despite ``restore_command`` being a GUC, one can still specify it in the ``postgresql.recovery_conf.restore_command`` section and Patroni will write it into ``postgresql.conf`` for PostgreSQL 12.
- Make it possible to use ``pg_rewind`` without superuser on PostgreSQL 11 and newer (Alexander Kukushkin)
If you want to use this feature please define ``username`` and ``password`` in the ``postgresql.authentication.rewind`` section of Patroni configuration file. For an already existing cluster you will have to create the user manually and ``GRANT EXECUTE`` permission on a few functions. You can find more details in the PostgreSQL `documentation <https://www.postgresql.org/docs/11/app-pgrewind.html#id-1.9.5.8.8>`__.
- Do a smart comparison of actual and desired ``primary_conninfo`` values on replicas (Alexander Kukushkin)
It might help to avoid replica restart when you are converting an already existing primary-standby cluster to one managed by Patroni
- IPv6 support (Alexander Kukushkin)
There were two major issues. Patroni REST API service was listening only on ``0.0.0.0`` and IPv6 IP addresses used in the ``api_url`` and ``conn_url`` were not properly quoted.
- Kerberos support (Ajith Vilas, Alexander Kukushkin)
It makes possible using Kerberos authentication between Postgres nodes instead of defining passwords in Patroni configuration file
- Manage ``pg_ident.conf`` (Alexander Kukushkin)
This functionality works similarly to ``pg_hba.conf``: if the ``postgresql.pg_ident`` is defined in the config file or DCS, Patroni will write its value to ``pg_ident.conf``, however, if ``postgresql.parameters.ident_file`` is defined, Patroni will assume that ``pg_ident`` is managed from outside and not update the file.
**Improvements in REST API**
- Added ``/health`` endpoint (Wilfried Roset)
It will return an HTTP status code only if PostgreSQL is running
- Added ``/read-only`` and ``/read-write`` endpoints (Julien Riou)
The ``/read-only`` endpoint enables reads balanced across replicas and the primary. The ``/read-write`` endpoint is an alias for ``/primary``, ``/leader`` and ``/master``.
- Use ``SSLContext`` to wrap the REST API socket (Julien Riou)
Usage of ``ssl.wrap_socket()`` is deprecated and was still allowing soon-to-be-deprecated protocols like TLS 1.1.
**Logging improvements**
- Two-step logging (Alexander Kukushkin)
All log messages are first written into the in-memory queue and later they are asynchronously flushed into the stderr or file from a separate thread. The maximum queue size is limited (configurable). If the limit is reached, Patroni will start losing logs, which is still better than blocking the HA loop.
- Enable debug logging for GET/OPTIONS API calls together with latency (Jan Tomsa)
It will help with debugging of health-checks performed by HAProxy, Consul or other tooling that decides which node is the primary/replica.
- Log exceptions caught in Retry (Daniel Kucera)
Log the final exception when either the number of attempts or the timeout were reached. It will hopefully help to debug some issues when communication to DCS fails.
**Improvements in patronictl**
- Enhance dialogues for scheduled switchover and restart (Rafia Sabih)
Previously dialogues did not take into account scheduled actions and therefore were misleading.
- Check if config file exists (Wilfried Roset)
Be verbose about configuration file when the given filename does not exists, instead of ignoring silently (which can lead to misunderstanding).
- Add fallback value for ``EDITOR`` (Wilfried Roset)
When the ``EDITOR`` environment variable was not defined, ``patronictl edit-config`` was failing with `PatroniCtlException`. The new strategy is to try ``editor`` and than ``vi``, which should be available on most systems.
**Improvements in Consul support**
- Allow to specify Consul consistency mode (Jan Tomsa)
You can read more about consistency mode `here <https://www.consul.io/api/features/consistency.html>`__.
- Reload Consul config on SIGHUP (Cameron Daniel, Alexander Kukushkin)
It is especially useful when somebody is changing the value of ``token``.
**Bugfixes**
- Fix corner case in switchover/failover (Sharoon Thomas)
The variable ``scheduled_at`` may be undefined if REST API is not accessible and we are using DCS as a fallback.
- Open trust to localhost in ``pg_hba.conf`` during custom bootstrap (Alexander Kukushkin)
Previously it was open only to unix_socket, which was causing a lot of errors: ``FATAL: no pg_hba.conf entry for replication connection from host "127.0.0.1", user "replicator"``
- Consider synchronous node as healthy even when the former leader is ahead (Alexander Kukushkin)
If the primary loses access to the DCS, it restarts Postgres in read-only, but it might happen that other nodes can still access the old primary via the REST API. Such a situation was causing the synchronous standby not to promote because the old primary was reporting WAL position ahead of the synchronous standby.
- Standby cluster bugfixes (Alexander Kukushkin)
Make it possible to bootstrap a replica in a standby cluster when the standby_leader is not accessible and a few other minor fixes.
Version 1.5.6
-------------
**New features**
- Support work with etcd cluster via set of proxies (Alexander Kukushkin)
It might happen that etcd cluster is not accessible directly but via set of proxies. In this case Patroni will not perform etcd topology discovery but just round-robin via proxy hosts. Behavior is controlled by `etcd.use_proxies`.
- Changed callbacks behavior when role on the node is changed (Alexander)
If the role was changed from `master` or `standby_leader` to `replica` or from `replica` to `standby_leader`, `on_restart` callback will not be called anymore in favor of `on_role_change` callback.
- Change the way how we start postgres (Alexander)
Use `multiprocessing.Process` instead of executing itself and `multiprocessing.Pipe` to transmit the postmaster pid to the Patroni process. Before that we were using pipes, what was leaving postmaster process with stdin closed.
**Bug fixes**
- Fix role returned by REST API for the standby leader (Alexander)
It was incorrectly returning `replica` instead of `standby_leader`
- Wait for callback end if it could not be killed (Julien Tachoires)
Patroni doesn't have enough privileges to terminate the callback script running under `sudo` what was cancelling the new callback. If the running script could not be killed, Patroni will wait until it finishes and then run the next callback.
- Reduce lock time taken by dcs.get_cluster method (Alexander)
Due to the lock being held DCS slowness was affecting the REST API health checks causing false positives.
- Improve cleaning of PGDATA when `pg_wal`/`pg_xlog` is a symlink (Julien)
In this case Patroni will explicitly remove files from the target directory.
- Remove unnecessary usage of os.path.relpath (Ants Aasma)
It depends on being able to resolve the working directory, what will fail if Patroni is started in a directory that is later unlinked from the filesystem.
- Do not enforce ssl version when communicating with Etcd (Alexander)
For some unknown reason python3-etcd on debian and ubuntu are not based on the latest version of the package and therefore it enforces TLSv1 which is not supported by Etcd v3. We solved this problem on Patroni side.
Version 1.5.5
-------------
This version introduces the possibility of automatic reinit of the former master, improves patronictl list output and fixes a number of bugs.
**New features**
- Add support of `PATRONI_ETCD_PROTOCOL`, `PATRONI_ETCD_USERNAME` and `PATRONI_ETCD_PASSWORD` environment variables (Étienne M)
Before it was possible to configure them only in the config file or as a part of `PATRONI_ETCD_URL`, which is not always convenient.
- Make it possible to automatically reinit the former master (Alexander Kukushkin)
If the pg_rewind is disabled or can't be used, the former master could fail to start as a new replica due to diverged timelines. In this case, the only way to fix it is wiping the data directory and reinitializing. This behavior could be changed by setting `postgresql.remove_data_directory_on_diverged_timelines`. When it is set, Patroni will wipe the data directory and reinitialize the former master automatically.
- Show information about timelines in patronictl list (Alexander)
It helps to detect stale replicas. In addition to that, `Host` will include ':{port}' if the port value isn't default or there is more than one member running on the same host.
- Create a headless service associated with the $SCOPE-config endpoint (Alexander)
The "config" endpoint keeps information about the cluster-wide Patroni and Postgres configuration, history file, and last but the most important, it holds the `initialize` key. When the Kubernetes master node is restarted or upgraded, it removes endpoints without services. The headless service will prevent it from being removed.
**Bug fixes**
- Adjust the read timeout for the leader watch blocking query (Alexander)
According to the Consul documentation, the actual response timeout is increased by a small random amount of additional wait time added to the supplied maximum wait time to spread out the wake up time of any concurrent requests. It adds up to `wait / 16` additional time to the maximum duration. In our case we are adding `wait / 15` or 1 second depending on what is bigger.
- Always use replication=1 when connecting via replication protocol to the postgres (Alexander)
Starting from Postgres 10 the line in the pg_hba.conf with database=replication doesn't accept connections with the parameter replication=database.
- Don't write primary_conninfo into recovery.conf for wal-only standby cluster (Alexander)
Despite not having neither `host` nor `port` defined in the `standby_cluster` config, Patroni was putting the `primary_conninfo` into the `recovery.conf`, which is useless and generating a lot of errors.
Version 1.5.4
-------------
This version implements flexible logging and fixes a number of bugs.
**New features**
- Improvements in logging infrastructure (Alexander Kukushkin, Lucas Capistrant, Alexander Anikin)
Logging configuration could be configured not only from environment variables but also from Patroni config file. It makes it possible to change logging configuration in runtime by updating config and doing reload or sending SIGHUP to the Patroni process. By default Patroni writes logs to stderr, but now it becomes possible to write logs directly into the file and rotate when it reaches a certain size. In addition to that added support of custom dateformat and the possibility to fine-tune log level for each python module.
- Make it possible to take into account the current timeline during leader elections (Alexander Kukushkin)
It could happen that the node is considering itself as a healthiest one although it is currently not on the latest known timeline. In some cases we want to avoid promoting of such node, which could be achieved by setting `check_timeline` parameter to `true` (default behavior remains unchanged).
- Relaxed requirements on superuser credentials
Libpq allows opening connections without explicitly specifying neither username nor password. Depending on situation it relies either on pgpass file or trust authentication method in pg_hba.conf. Since pg_rewind is also using libpq, it will work the same way.
- Implemented possibility to configure Consul Service registration and check interval via environment variables (Alexander Kukushkin)
Registration of service in Consul was added in the 1.5.0, but so far it was only possible to turn it on via patroni.yaml.
**Stability Improvements**
- Set archive_mode to off during the custom bootstrap (Alexander Kukushkin)
We want to avoid archiving wals and history files until the cluster is fully functional. It really helps if the custom bootstrap involves pg_upgrade.
- Apply five seconds backoff when loading global config on start (Alexander Kukushkin)
It helps to avoid hammering DCS when Patroni just starting up.
- Reduce amount of error messages generated on shutdown (Alexander Kukushkin)
They were harmless but rather annoying and sometimes scary.
- Explicitly secure rw perms for recovery.conf at creation time (Lucas)
We don't want anybody except patroni/postgres user reading this file, because it contains replication user and password.
- Redirect HTTPServer exceptions to logger (Julien Riou)
By default, such exceptions were logged on standard output messing with regular logs.
**Bug fixes**
- Removed stderr pipe to stdout on pg_ctl process (Cody Coons)
Inheriting stderr from the main Patroni process allows all Postgres logs to be seen along with all patroni logs. This is very useful in a container environment as Patroni and Postgres logs may be consumed using standard tools (docker logs, kubectl, etc). In addition to that, this change fixes a bug with Patroni not being able to catch postmaster pid when postgres writing some warnings into stderr.
- Set Consul service check deregister timeout in Go time format (Pavel Kirillov)
Without explicitly mentioned time unit registration was failing.
- Relax checks of standby_cluster cluster configuration (Dmitry Dolgov, Alexander Kukushkin)
It was accepting only strings as valid values and therefore it was not possible to specify the port as integer and create_replica_methods as a list.
Version 1.5.3
-------------
Compatibility and bugfix release.
- Improve stability when running with python3 against zookeeper (Alexander Kukushkin)
Change of `loop_wait` was causing Patroni to disconnect from zookeeper and never reconnect back.
- Fix broken compatibility with postgres 9.3 (Alexander)
When opening a replication connection we should specify replication=1, beacuse 9.3 does not understand replication='database'
- Make sure we refresh Consul session at least once per HA loop and improve handling of consul sessions exceptions (Alexander)
Restart of local consul agent invalidates all sessions related to the node. Not calling session refresh on time and not doing proper handling of session errors was causing demote of the primary.
Version 1.5.2
-------------
Compatibility and bugfix release.
- Compatibility with kazoo-2.6.0 (Alexander Kukushkin)
In order to make sure that requests are performed with an appropriate timeout, Patroni redefines create_connection method from python-kazoo module. The last release of kazoo slightly changed the way how create_connection method is called.
- Fix Patroni crash when Consul cluster loses the leader (Alexander)
The crash was happening due to incorrect implementation of touch_member method, it should return boolean and not raise any exceptions.
Version 1.5.1
-------------
This version implements support of permanent replication slots, adds support of pgBackRest and fixes number of bugs.
**New features**
- Permanent replication slots (Alexander Kukushkin)
Permanent replication slots are preserved on failover/switchover, that is, Patroni on the new primary will create configured replication slots right after doing promote. Slots could be configured with the help of `patronictl edit-config`. The initial configuration could be also done in the :ref:`bootstrap.dcs <settings>`.
- Add pgbackrest support (Yogesh Sharma)
pgBackrest can restore in existing $PGDATA folder, this allows speedy restore as files which have not changed since last backup are skipped, to support this feature new parameter `keep_data` has been introduced. See :ref:`replica creation method <custom_replica_creation>` section for additional examples.
**Bug fixes**
- A few bugfixes in the "standby cluster" workflow (Alexander)
Please see https://github.com/zalando/patroni/pull/823 for more details.
- Fix REST API health check when cluster management is paused and DCS is not accessible (Alexander)
Regression was introduced in https://github.com/zalando/patroni/commit/90cf930036a9d5249265af15d2b787ec7517cf57
Version 1.5.0
-------------
This version enables Patroni HA cluster to operate in a standby mode, introduces experimental support for running on Windows, and provides a new configuration parameter to register PostgreSQL service in Consul.
**New features**
- Standby cluster (Dmitry Dolgov)
One or more Patroni nodes can form a standby cluster that runs alongside the primary one (i.e. in another datacenter) and consists of standby nodes that replicate from the master in the primary cluster. All PostgreSQL nodes in the standby cluster are replicas; one of those replicas elects itself to replicate directly from the remote master, while the others replicate from it in a cascading manner. More detailed description of this feature and some configuration examples can be found at :ref:`here <standby_cluster>`.
- Register Services in Consul (Pavel Kirillov, Alexander Kukushkin)
If `register_service` parameter in the consul :ref:`configuration <consul_settings>` is enabled, the node will register a service with the name `scope` and the tag `master`, `replica` or `standby-leader`.
- Experimental Windows support (Pavel Golub)
From now on it is possible to run Patroni on Windows, although Windows support is brand-new and hasn't received as much real-world testing as its Linux counterpart. We welcome your feedback!
**Improvements in patronictl**
- Add patronictl -k/--insecure flag and support for restapi cert (Wilfried Roset)
In the past if the REST API was protected by the self-signed certificates `patronictl` would fail to verify them. There was no way to disable that verification. It is now possible to configure `patronictl` to skip the certificate verification altogether or provide CA and client certificates in the :ref:`ctl: <patronictl_settings>` section of configuration.
- Exclude members with nofailover tag from patronictl switchover/failover output (Alexander Anikin)
Previously, those members were incorrectly proposed as candidates when performing interactive switchover or failover via patronictl.
**Stability improvements**
- Avoid parsing non-key-value output lines of pg_controldata (Alexander Anikin)
Under certain circuimstances pg_controldata outputs lines without a colon character. That would trigger an error in Patroni code that parsed pg_controldata output, hiding the actual problem; often such lines are emitted in a warning shown by pg_controldata before the regular output, i.e. when the binary major version does not match the one of the PostgreSQL data directory.
- Add member name to the error message during the leader election (Jan Mussler)
During the leader election, Patroni connects to all known members of the cluster and requests their status. Such status is written to the Patroni log and includes the name of the member. Previously, if the member was not accessible, the error message did not indicate its name, containing only the URL.
- Immediately reserve the WAL position upon creation of the replication slot (Alexander Kukushkin)
Starting from 9.6, `pg_create_physical_replication_slot` function provides an additional boolean parameter `immediately_reserve`. When it is set to `false`, which is also the default, the slot doesn't reserve the WAL position until it receives the first client connection, potentially losing some segments required by the client in a time window between the slot creation and the intiial client connection.
- Fix bug in strict synchronous replication (Alexander Kukushkin)
When running with `synchronous_mode_strict: true`, in some cases Patroni puts `*` into the `synchronous_standby_names`, changing the sync state for most of the replication connections to `potential`. Previously, Patroni couldn't pick a synchronous candidate under such curcuimstances, as it only considered those with the state `async`.
Version 1.4.6
-------------
**Bug fixes and stability improvements**
This release fixes a critical issue with Patroni API /master endpoint returning 200 for the non-master node. This is a
reporting issue, no actual split-brain, but under certain circumstances clients might be directed to the read-only node.
- Reset is_leader status on demote (Alexander Kukushkin, Oleksii Kliukin)
Make sure demoted cluster member stops responding with code 200 on the /master API call.
- Add new "cluster_unlocked" field to the API output (Dmitry Dolgov)
This field indicates whether the cluster has the master running. It can be used when it is not possible to query any
other node but one of the replicas.
Version 1.4.5
-------------
**New features**
- Improve logging when applying new postgres configuration (Don Seiler)
Patroni logs changed parameter names and values.
- Python 3.7 compatibility (Christoph Berg)
async is a reserved keyword in python3.7
- Set state to "stopped" in the DCS when a member is shut down (Tony Sorrentino)
This shows the member state as "stopped" in "patronictl list" command.
- Improve the message logged when stale postmaster.pid matches a running process (Ants Aasma)
The previous one was beyond confusing.
- Implement patronictl reload functionality (Don Seiler)
Before that it was only possible to reload configuration by either calling REST API or by sending SIGHUP signal to the Patroni process.
- Take and apply some parameters from controldata when starting as a replica (Alexander Kukushkin)
The value of `max_connections` and some other parameters set in the global configuration may be lower than the one actually used by the primary; when this happens, the replica cannot start and should be fixed manually. Patroni takes care of that now by reading and applying the value from `pg_controldata`, starting postgres and setting `pending_restart` flag.
- If set, use LD_LIBRARY_PATH when starting postgres (Chris Fraser)
When starting up Postgres, Patroni was passing along PATH, LC_ALL and LANG env vars if they are set. Now it is doing the same with LD_LIBRARY_PATH. It should help if somebody installed PostgreSQL to non-standard place.
- Rename create_replica_method to create_replica_methods (Dmitry Dolgov)
To make it clear that it's actually an array. The old name is still supported for backward compatibility.
**Bug fixes and stability improvements**
- Fix condition for the replica start due to pg_rewind in paused state (Oleksii Kliukin)
Avoid starting the replica that had already executed pg_rewind before.
- Respond 200 to the master health-check only if update_lock has been successful (Alexander)
Prevent Patroni from reporting itself a master on the former (demoted) master if DCS is partitioned.
- Fix compatibility with the new consul module (Alexander)
Starting from v1.1.0 python-consul changed internal API and started using `list` instead of `dict` to pass query parameters.
- Catch exceptions from Patroni REST API thread during shutdown (Alexander)
Those uncaught exceptions kept PostgreSQL running at shutdown.
- Do crash recovery only when Postgres runs as the master (Alexander)
Require `pg_controldata` to report 'in production' or 'shutting down' or 'in crash recovery'. In all other cases no crash recovery is necessary.
- Improve handling of configuration errors (Henning Jacobs, Alexander)
It is possible to change a lot of parameters in runtime (including `restapi.listen`) by updating Patroni config file and sending SIGHUP to Patroni process. This fix eliminates obscure exceptions from the 'restapi' thread when some of the parameters receive invalid values.
Version 1.4.4
-------------
**Stability improvements**
- Fix race condition in poll_failover_result (Alexander Kukushkin)
It didn't affect directly neither failover nor switchover, but in some rare cases it was reporting success too early, when the former leader released the lock, producing a 'Failed over to "None"' instead of 'Failed over to "desired-node"' message.
- Treat Postgres parameter names as case insensitive (Alexander)
Most of the Postgres parameters have snake_case names, but there are three exceptions from this rule: DateStyle, IntervalStyle and TimeZone. Postgres accepts those parameters when written in a different case (e.g. timezone = 'some/tzn'); however, Patroni was unable to find case-insensitive matches of those parameter names in pg_settings and ignored such parameters as a result.
- Abort start if attaching to running postgres and cluster not initialized (Alexander)
Patroni can attach itself to an already running Postgres instance. It is imperative to start running Patroni on the master node before getting to the replicas.
- Fix behavior of patronictl scaffold (Alexander)
Pass dict object to touch_member instead of json encoded string, DCS implementation will take care of encoding it.
- Don't demote master if failed to update leader key in pause (Alexander)
During maintenance a DCS may start failing write requests while continuing to responds to read ones. In that case, Patroni used to put the Postgres master node to a read-only mode after failing to update the leader lock in DCS.
- Sync replication slots when Patroni notices a new postmaster process (Alexander)
If Postgres has been restarted, Patroni has to make sure that list of replication slots matches its expectations.
- Verify sysid and sync replication slots after coming out of pause (Alexander)
During the `maintenance` mode it may happen that data directory was completely rewritten and therefore we have to make sure that `Database system identifier` still belongs to our cluster and replication slots are in sync with Patroni expectations.
- Fix a possible failure to start not running Postgres on a data directory with postmaster lock file present (Alexander)
Detect reuse of PID from the postmaster lock file. More likely to hit such problem if you run Patroni and Postgres in the docker container.
- Improve protection of DCS being accidentally wiped (Alexander)
Patroni has a lot of logic in place to prevent failover in such case; it can also restore all keys back; however, until this change an accidental removal of /config key was switching off pause mode for 1 cycle of HA loop.
- Do not exit when encountering invalid system ID (Oleksii Kliukin)
Do not exit when the cluster system ID is empty or the one that doesn't pass the validation check. In that case, the cluster most likely needs a reinit; mention it in the result message. Avoid terminating Patroni, as otherwise reinit cannot happen.
**Compatibility with Kubernetes 1.10+**
- Added check for empty subsets (Cody Coons)
Kubernetes 1.10.0+ started returning `Endpoints.subsets` set to `None` instead of `[]`.
**Bootstrap improvements**
- Make deleting recovery.conf optional (Brad Nicholson)
If `bootstrap.<custom_bootstrap_method_name>.keep_existing_recovery_conf` is defined and set to ``True``, Patroni will not remove the existing ``recovery.conf`` file. This is useful when bootstrapping from a backup with tools like pgBackRest that generate the appropriate `recovery.conf` for you.
- Allow options to the basebackup built-in method (Oleksii)
It is now possible to supply options to the built-in basebackup method by defining the `basebackup` section in the configuration, similar to how those are defined for custom replica creation methods. The difference is in the format accepted by the `basebackup` section: since pg_basebackup accepts both `--key=value` and `--key` options, the contents of the section could be either a dictionary of key-value pairs, or a list of either one-element dictionaries or just keys (for the options that don't accept values). See :ref:`replica creation method <custom_replica_creation>` section for additional examples.
Version 1.4.3
-------------
**Improvements in logging**
- Make log level configurable from environment variables (Andy Newton, Keyvan Hedayati)
`PATRONI_LOGLEVEL` - sets the general logging level
`PATRONI_REQUESTS_LOGLEVEL` - sets the logging level for all HTTP requests e.g. Kubernetes API calls
See `the docs for Python logging <https://docs.python.org/3.6/library/logging.html#levels>` to get the names of possible log levels
**Stability improvements and bug fixes**
- Don't rediscover etcd cluster topology when watch timed out (Alexander Kukushkin)
If we have only one host in etcd configuration and exactly this host is not accessible, Patroni was starting discovery of cluster topology and never succeeding. Instead it should just switch to the next available node.
- Write content of bootstrap.pg_hba into a pg_hba.conf after custom bootstrap (Alexander)
Now it behaves similarly to the usual bootstrap with `initdb`
- Single user mode was waiting for user input and never finish (Alexander)
Regression was introduced in https://github.com/zalando/patroni/pull/576
Version 1.4.2 Version 1.4.2
------------- -------------
@@ -82,8 +606,8 @@ In addition to using Endpoints, Patroni supports ConfigMaps. You can find more i
- Minimize the amount of SELECT's issued by Patroni on every loop of HA cylce (Alexander Kukushkin) - Minimize the amount of SELECT's issued by Patroni on every loop of HA cylce (Alexander Kukushkin)
On every iteration of HA loop Patroni needs to know recovery status and absolute wal position. From now on Patroni will run only single SELECT to get this information instead of two on the replica and three on the master. On every iteration of HA loop Patroni needs to know recovery status and absolute wal position. From now on Patroni will run only single SELECT to get this information instead of two on the replica and three on the master.
- Remove leader key on shutdown only when we have the lock (Ants) - Remove leader key on shutdown only when we have the lock (Ants)
Unconditional removal was generating unnecessary and missleading exceptions. Unconditional removal was generating unnecessary and missleading exceptions.
@@ -93,7 +617,7 @@ In addition to using Endpoints, Patroni supports ConfigMaps. You can find more i
- Add version command to patronictl (Ants) - Add version command to patronictl (Ants)
It will show the version of installed Patroni and versions of running Patroni instances (if the cluster name is specified). It will show the version of installed Patroni and versions of running Patroni instances (if the cluster name is specified).
- Make optional specifying cluster_name argument for some of patronictl commands (Alexander, Ants) - Make optional specifying cluster_name argument for some of patronictl commands (Alexander, Ants)
It will work if patronictl is using usual Patroni configuration file with the ``scope`` defined. It will work if patronictl is using usual Patroni configuration file with the ``scope`` defined.
@@ -101,11 +625,11 @@ In addition to using Endpoints, Patroni supports ConfigMaps. You can find more i
- Show information about scheduled switchover and maintenance mode (Alexander) - Show information about scheduled switchover and maintenance mode (Alexander)
Before that it was possible to get this information only from Patroni logs or directly from DCS. Before that it was possible to get this information only from Patroni logs or directly from DCS.
- Improve ``patronictl reinit`` (Alexander) - Improve ``patronictl reinit`` (Alexander)
Sometimes ``patronictl reinit`` refused to proceed when Patroni was busy with other actions, namely trying to start postgres. `patronictl` didn't provide any commands to cancel such long running actions and the only (dangerous) workarond was removing a data directory manually. The new implementation of `reinit` forcefully cancells other long-running actions before proceeding with reinit. Sometimes ``patronictl reinit`` refused to proceed when Patroni was busy with other actions, namely trying to start postgres. `patronictl` didn't provide any commands to cancel such long running actions and the only (dangerous) workarond was removing a data directory manually. The new implementation of `reinit` forcefully cancells other long-running actions before proceeding with reinit.
- Implement ``--wait`` flag in ``patronictl pause`` and ``patronictl resume`` (Alexander) - Implement ``--wait`` flag in ``patronictl pause`` and ``patronictl resume`` (Alexander)
It will make ``patronictl`` wait until the requested action is acknowledged by all nodes in the cluster. It will make ``patronictl`` wait until the requested action is acknowledged by all nodes in the cluster.
@@ -152,7 +676,7 @@ Version 1.3.6
After a crash that doesn't clean up postmaster.pid there could be a new process with the same pid, resulting in a false positive for is_running(), which will lead to all kinds of bad behavior. After a crash that doesn't clean up postmaster.pid there could be a new process with the same pid, resulting in a false positive for is_running(), which will lead to all kinds of bad behavior.
- Shutdown postgresql before bootstrap when we lost data directory (ainlolcat) - Shutdown postgresql before bootstrap when we lost data directory (ainlolcat)
When data directory on the master is forcefully removed, postgres process can still stay alive for some time and prevent the replica created in place of that former master from starting or replicating. When data directory on the master is forcefully removed, postgres process can still stay alive for some time and prevent the replica created in place of that former master from starting or replicating.
The fix makes Patroni cache the postmaster pid and its start time and let it terminate the old postmaster in case it is still running after the corresponding data directory has been removed. The fix makes Patroni cache the postmaster pid and its start time and let it terminate the old postmaster in case it is still running after the corresponding data directory has been removed.
@@ -222,7 +746,7 @@ Version 1.3.4
- Pass the consul token as a header (Andrew Colin Kissa) - Pass the consul token as a header (Andrew Colin Kissa)
Headers are now the prefered way to pass the token to the consul `API <https://www.consul.io/api/index.html#authentication>`__. Headers are now the prefered way to pass the token to the consul `API <https://www.consul.io/api/index.html#authentication>`__.
- Advanced configuration for Consul (Alexander Kukushkin) - Advanced configuration for Consul (Alexander Kukushkin)
+117 -7
View File
@@ -3,7 +3,7 @@ Replica imaging and bootstrap
Patroni allows customizing creation of a new replica. It also supports defining what happens when the new empty cluster Patroni allows customizing creation of a new replica. It also supports defining what happens when the new empty cluster
is being bootstrapped. The distinction between two is well defined: Patroni creates replicas only if the ``initialize`` is being bootstrapped. The distinction between two is well defined: Patroni creates replicas only if the ``initialize``
key is present in Etcd for the cluster. If there is no ``initialize`` key - Patroni calls bootstrap exclusively on the key is present in DCS for the cluster. If there is no ``initialize`` key - Patroni calls bootstrap exclusively on the
first node that takes the initialize key lock. first node that takes the initialize key lock.
.. _custom_bootstrap: .. _custom_bootstrap:
@@ -23,6 +23,7 @@ arguments to them, i.e. the name of the cluster and the path to the data directo
method: <custom_bootstrap_method_name> method: <custom_bootstrap_method_name>
<custom_bootstrap_method_name>: <custom_bootstrap_method_name>:
command: <path_to_custom_bootstrap_script> [param1 [, ...]] command: <path_to_custom_bootstrap_script> [param1 [, ...]]
keep_existing_recovery_conf: False
recovery_conf: recovery_conf:
recovery_target_action: promote recovery_target_action: promote
recovery_target_timeline: latest recovery_target_timeline: latest
@@ -47,6 +48,9 @@ If a ``recovery_conf`` block is defined in the same section as the custom bootst
``recovery.conf`` before starting the newly bootstrapped instance. Typically, such recovery.conf should contain at least ``recovery.conf`` before starting the newly bootstrapped instance. Typically, such recovery.conf should contain at least
one of the ``recovery_target_*`` parameters, together with the ``recovery_target_timeline`` set to ``promote``. one of the ``recovery_target_*`` parameters, together with the ``recovery_target_timeline`` set to ``promote``.
If ``keep_existing_recovery_conf`` is defined and set to ``True``, Patroni will not remove the existing ``recovery.conf`` file if it exists.
This is useful when bootstrapping from a backup with tools like pgBackRest that generate the appropriate ``recovery.conf`` for you.
.. note:: Bootstrap methods are neither chained, nor fallen-back to the default one in case the primary one fails .. note:: Bootstrap methods are neither chained, nor fallen-back to the default one in case the primary one fails
@@ -64,7 +68,20 @@ scripts to clone a new replica. Those are configured in the ``postgresql`` confi
.. code:: YAML .. code:: YAML
postgresql: postgresql:
create_replica_method: create_replica_methods:
- <method name>
<method name>:
command: <command name>
keep_data: True
no_params: True
no_master: 1
example: wal_e
.. code:: YAML
postgresql:
create_replica_methods:
- wal_e - wal_e
- basebackup - basebackup
wal_e: wal_e:
@@ -72,13 +89,29 @@ scripts to clone a new replica. Those are configured in the ``postgresql`` confi
no_master: 1 no_master: 1
envdir: {{WALE_ENV_DIR}} envdir: {{WALE_ENV_DIR}}
use_iam: 1 use_iam: 1
basebackup:
max-rate: '100M'
example: pgbackrest
.. code:: YAML
postgresql:
create_replica_methods:
- pgbackrest
- basebackup
pgbackrest:
command: /usr/bin/pgbackrest --stanza=<scope> --delta restore
keep_data: True
no_params: True
basebackup:
max-rate: '100M'
The ``create_replica_method`` defines available replica creation methods and the order of executing them. Patroni will The ``create_replica_methods`` defines available replica creation methods and the order of executing them. Patroni will
stop on the first one that returns 0. The basebackup is the built-in method and doesn't require any configuration. The stop on the first one that returns 0. Each method should define a separate section in the configuration file, listing the command
rest of the methods should define a separate section in the configuration file, listing the command to execute and any to execute and any custom parameters that should be passed to that command. All parameters will be passed in a
custom parameters that should be passed to that command. All parameters will be passed in a ``--name=value`` format. ``--name=value`` format. Besides user-defined parameters, Patroni supplies a couple of cluster-specific ones:
Besides user-defined parameters, Patroni supplies a couple of cluster-specific ones:
--scope --scope
Which cluster this replica belongs to Which cluster this replica belongs to
@@ -94,4 +127,81 @@ A special ``no_master`` parameter, if defined, allows Patroni to call the replic
running master or replicas. In that case, an empty string will be passed in a connection string. This is useful for running master or replicas. In that case, an empty string will be passed in a connection string. This is useful for
restoring the formerly running cluster from the binary backup. restoring the formerly running cluster from the binary backup.
A special ``keep_data`` parameter, if defined, will instuct Patroni to not clean PGDATA folder before calling restore.
A special ``no_params`` parameter, if defined, restricts passing parameters to custom command.
A ``basebackup`` method is a special case: it will be used if
``create_replica_methods`` is empty, although it is possible
to list it explicitly among the ``create_replica_methods`` methods. This method initializes a new replica with the
``pg_basebackup``, the base backup is taken from the master unless there are replicas with ``clonefrom`` tag, in which case one
of such replicas will be used as the origin for pg_basebackup. It works without any configuration; however, it is
possible to specify a ``basebackup`` configuration section. Same rules as with the other method configuration apply,
namely, only long (with --) options should be specified there. Not all parameters make sense, if you override a connection
string or provide an option to created tar-ed or compressed base backups, patroni won't be able to make a replica out
of it. There is no validation performed on the names or values of the parameters passed to the ``basebackup`` section.
You can specify basebackup parameters as either a map (key-value pairs) or a list of elements, where each element
could be either a key-value pair or a single key (for options that does not receive any values, for instance, ``--verbose``).
Consider those 2 examples:
.. code:: YAML
postgresql:
basebackup:
max-rate: '100M'
checkpoint: 'fast'
and
.. code:: YAML
postgresql:
basebackup:
- verbose
- max-rate: '100M'
If all replica creation methods fail, Patroni will try again all methods in order during the next event loop cycle. If all replica creation methods fail, Patroni will try again all methods in order during the next event loop cycle.
.. _standby_cluster:
Standby cluster
---------------
Another available option is to run a "standby cluster", that contains only of
standby nodes replicating from some remote master. This type of clusters has:
* "standby leader", that behaves pretty much like a regular cluster leader,
except it replicates from a remote master.
* cascade replicas, that are replicating from standby leader.
Standby leader holds and updates a leader lock in DCS. If the leader lock
expires, cascade replicas will perform an election to choose another leader
from the standbys.
For the sake of flexibility, you can specify methods of creating a replica and
recovery WAL records when a cluster is in the "standby mode" by providing
`create_replica_methods` key in `standby_cluster` section. It is distinct from
creating replicas, when cluster is detached and functions as a normal cluster,
which is controlled by `create_replica_methods` in `postgresql` section. Both
"standby" and "normal" `create_replica_methods` reference keys in `postgresql`
section.
To configure such cluster you need to specify the section ``standby_cluster``
in a patroni configuration:
.. code:: YAML
bootstrap:
dcs:
standby_cluster:
host: 1.2.3.4
port: 5432
primary_slot_name: patroni
create_replica_methods:
- basebackup
Note, that these options will be applied only once during cluster bootstrap,
and the only way to change them afterwards is through DCS.
If you use replication slots on the standby cluster, you must also create the corresponding replication slot on the primary cluster. It will not be done automatically by the standby cluster implementation. You can use Patroni's permenant replication slots feature on the primary cluster to maintain a replication slot with the same name as ``primary_slot_name``, or its default value if ``primary_slot_name`` is not provided.
+21 -10
View File
@@ -9,9 +9,11 @@ Patroni uses PostgreSQL streaming replication. For more information about stream
Asynchronous mode durability Asynchronous mode durability
---------------------------- ----------------------------
In asynchronous mode the cluster is allowed to lose some committed transactions to ensure availability. When master server fails or becomes unavailable for any other reason Patroni will automatically promote a sufficiently healthy standby to master. Any transactions that have not been replicated to that standby remain in a "forked timeline" on the master, and are effectively unrecoverable [1]_. In asynchronous mode the cluster is allowed to lose some committed transactions to ensure availability. When the primary server fails or becomes unavailable for any other reason Patroni will automatically promote a sufficiently healthy standby to primary. Any transactions that have not been replicated to that standby remain in a "forked timeline" on the primary, and are effectively unrecoverable [1]_.
The amount of transactions that can be lost is controlled via ``maximum_lag_on_failover`` parameter. Because master transaction log position is not sampled in real time, in reality the amount of lost data on failover is worst case bounded by ``maximum_lag_on_failover`` bytes of transaction log plus the amount that is written in the last ``ttl`` seconds (``loop_wait``/2 seconds in the average case). However typical steady state replication delay is well under a second. The amount of transactions that can be lost is controlled via ``maximum_lag_on_failover`` parameter. Because the primary transaction log position is not sampled in real time, in reality the amount of lost data on failover is worst case bounded by ``maximum_lag_on_failover`` bytes of transaction log plus the amount that is written in the last ``ttl`` seconds (``loop_wait``/2 seconds in the average case). However typical steady state replication delay is well under a second.
By default, when running leader elections, Patroni does not take into account the current timeline of replicas, what in some cases could be undesirable behavior. You can prevent the node not having the same timeline as a former master become the new leader by changing the value of ``check_timeline`` parameter to ``true``.
PostgreSQL synchronous replication PostgreSQL synchronous replication
---------------------------------- ----------------------------------
@@ -20,7 +22,7 @@ You can use Postgres's `synchronous replication <http://www.postgresql.org/docs/
In hosted datacenter environments (like AWS, Rackspace, or any network you do not control), synchronous replication significantly increases the variability of write performance. If followers become inaccessible from the leader, the leader effectively becomes read-only. In hosted datacenter environments (like AWS, Rackspace, or any network you do not control), synchronous replication significantly increases the variability of write performance. If followers become inaccessible from the leader, the leader effectively becomes read-only.
To enable a simple synchronous replication test, add the follow lines to the ``parameters`` section of your YAML configuration files: To enable a simple synchronous replication test, add the following lines to the ``parameters`` section of your YAML configuration files:
.. code:: YAML .. code:: YAML
@@ -29,18 +31,27 @@ To enable a simple synchronous replication test, add the follow lines to the ``p
When using PostgreSQL synchronous replication, use at least three Postgres data nodes to ensure write availability if one host fails. When using PostgreSQL synchronous replication, use at least three Postgres data nodes to ensure write availability if one host fails.
Using PostgreSQL synchronous replication does not guarantee zero lost transactions under all circumstances. When master and standby that is currently acting as synchronous fail simultaneously a third node that might not contain all transactions will be promoted. Using PostgreSQL synchronous replication does not guarantee zero lost transactions under all circumstances. When the primary and the secondary that is currently acting as a synchronous replica fail simultaneously a third node that might not contain all transactions will be promoted.
.. _synchronous_mode: .. _synchronous_mode:
Synchronous mode Synchronous mode
---------------- ----------------
For use cases where losing committed transactions is not permissible you can turn on Patronis ``synchronous_mode``. When ``synchronous_mode`` is turned on Patroni will not promote a standby unless it is certain that the standby contains all transactions that may have returned a successful commit status to client [2]_. This means that the system may be unavailable for writes even though some servers are available. System administrators can still use manual failover commmands to promote a standby even if it results in transaction loss. For use cases where losing committed transactions is not permissible you can turn on Patroni's ``synchronous_mode``. When ``synchronous_mode`` is turned on Patroni will not promote a standby unless it is certain that the standby contains all transactions that may have returned a successful commit status to client [2]_. This means that the system may be unavailable for writes even though some servers are available. System administrators can still use manual failover commands to promote a standby even if it results in transaction loss.
Turning on ``synchronous_mode`` does not guarantee multi node durability of commits under all circumstances. When no suitable standby is available, master server will still accept writes, but does not guarantee their replication. When the master fails in this mode no standby will be promote. When the host that used to be master comes back it will get promoted automatically, unless system administrator performed a manual failover. This behavior makes synchronous mode usable with 2 node clusters. Turning on ``synchronous_mode`` does not guarantee multi node durability of commits under all circumstances. When no suitable standby is available, primary server will still accept writes, but does not guarantee their replication. When the primary fails in this mode no standby will be promoted. When the host that used to be the primary comes back it will get promoted automatically, unless system administrator performed a manual failover. This behavior makes synchronous mode usable with 2 node clusters.
When ``synchronous_mode`` is on and a standby crashes, commits will block until next iteration of Patroni runs and switches master to standalone mode (worst case delay for writes ``ttl`` seconds, average case ``loop_wait``/2 seconds). Manually shutting down or restarting a standby will not cause a commit service interruption. Standby will signal the master to release itself from synchronous standby duties before PostgreSQL shutdown is initiated. When ``synchronous_mode`` is on and a standby crashes, commits will block until next iteration of Patroni runs and switches the primary to standalone mode (worst case delay for writes ``ttl`` seconds, average case ``loop_wait``/2 seconds). Manually shutting down or restarting a standby will not cause a commit service interruption. Standby will signal the primary to release itself from synchronous standby duties before PostgreSQL shutdown is initiated.
When it is absolutely necessary to guarantee that each write is stored durably
on at least two nodes, enable ``synchronous_mode_strict`` in addition to the
``synchronous_node``. This parameter prevents Patroni from switching off the
synchronous replication on the primary when no synchronous standby candidates
are available. As a downside, the primary is not be available for writes
(unless the Postgres transaction explicitly turns of ``synchronous_mode``),
blocking all client write requests until at least one synchronous replica comes
up.
You can ensure that a standby never becomes the synchronous standby by setting ``nosync`` tag to true. This is recommended to set for standbys that are behind slow network connections and would cause performance degradation when becoming a synchronous standby. You can ensure that a standby never becomes the synchronous standby by setting ``nosync`` tag to true. This is recommended to set for standbys that are behind slow network connections and would cause performance degradation when becoming a synchronous standby.
@@ -50,7 +61,7 @@ Synchronous mode can be switched on and off via Patroni REST interface. See :ref
Synchronous mode implementation Synchronous mode implementation
------------------------------- -------------------------------
When in synchronous mode Patroni maintains synchronization state in the DCS, containing the latest master and current synchronous standby. This state is updated with strict ordering constraints to ensure the following invariants: When in synchronous mode Patroni maintains synchronization state in the DCS, containing the latest primary and current synchronous standby. This state is updated with strict ordering constraints to ensure the following invariants:
- A node must be marked as the latest leader whenever it can accept write transactions. Patroni crashing or PostgreSQL not shutting down can cause violations of this invariant. - A node must be marked as the latest leader whenever it can accept write transactions. Patroni crashing or PostgreSQL not shutting down can cause violations of this invariant.
@@ -60,9 +71,9 @@ When in synchronous mode Patroni maintains synchronization state in the DCS, con
Patroni will only ever assign one standby to ``synchronous_standby_names`` because with multiple candidates it is not possible to know which node was acting as synchronous during the failure. Patroni will only ever assign one standby to ``synchronous_standby_names`` because with multiple candidates it is not possible to know which node was acting as synchronous during the failure.
On each HA loop iteration Patroni re-evaluates synchronous standby choice. If the current synchronous standby is connected and has not requested its synchronous status to be removed it remains picked. Otherwise the cluster member avaiable for sync that is furthest ahead in replication is picked. On each HA loop iteration Patroni re-evaluates synchronous standby choice. If the current synchronous standby is connected and has not requested its synchronous status to be removed it remains picked. Otherwise the cluster member available for sync that is furthest ahead in replication is picked.
.. [1] The data is still there, but recovering it requires a manual recovery effort by data recovery specialists. When Patroni is allowed to rewind with ``use_pg_rewind`` the forked timeline will be automatically erased to rejoin the failed master with the cluster. .. [1] The data is still there, but recovering it requires a manual recovery effort by data recovery specialists. When Patroni is allowed to rewind with ``use_pg_rewind`` the forked timeline will be automatically erased to rejoin the failed primary with the cluster.
.. [2] Clients can change the behavior per transaction using PostgreSQL's ``synchronous_commit`` setting. Transactions with ``synchronous_commit`` values of ``off`` and ``local`` may be lost on fail over, but will not be blocked by replication delays. .. [2] Clients can change the behavior per transaction using PostgreSQL's ``synchronous_commit`` setting. Transactions with ``synchronous_commit`` values of ``off`` and ``local`` may be lost on fail over, but will not be blocked by replication delays.
+1 -1
View File
@@ -9,7 +9,7 @@ Having multiple PostgreSQL servers running as master can result in transactions
- Shutting down PostgreSQL is too slow. - Shutting down PostgreSQL is too slow.
- Patroni does not get to run due to high load on the system, th VM being paused by the hypervisor, or other infrastructure issues. - Patroni does not get to run due to high load on the system, the VM being paused by the hypervisor, or other infrastructure issues.
To guarantee correct behavior under these conditions Patroni supports watchdog devices. Watchdog devices are software or hardware mechanisms that will reset the whole system when they do not get a keepalive heartbeat within a specified timeframe. This adds an additional layer of fail safe in case usual Patroni split-brain protection mechanisms fail. To guarantee correct behavior under these conditions Patroni supports watchdog devices. Watchdog devices are software or hardware mechanisms that will reset the whole system when they do not get a keepalive heartbeat within a specified timeframe. This adds an additional layer of fail safe in case usual Patroni split-brain protection mechanisms fail.
+3 -3
View File
@@ -1,11 +1,11 @@
### confd ### confd
`confd` directory contains haproxy template files for the [confd](https://github.com/kelseyhightower/confd) -- lightweight configuration management tool `confd` directory contains haproxy and pgbouncer template files for the [confd](https://github.com/kelseyhightower/confd) -- lightweight configuration management tool
You need to copy content of `confd` directory into /etcd/confd and run confd service: You need to copy content of `confd` directory into /etcd/confd and run confd service:
```bash ```bash
$ confd -prefix=/service/$PATRONI_SCOPE -backend etcd -node $PATRONI_ETCD_HOST -interval=10 $ confd -prefix=/service/$PATRONI_SCOPE -backend etcd -node $PATRONI_ETCD_URL -interval=10
``` ```
It will periodically update haproxy.cfg with the actual list of Patroni nodes from `etcd` and "reload" haproxy when it is necessary. It will periodically update haproxy.cfg and pgbouncer.ini with the actual list of Patroni nodes from `etcd` and "reload" haproxy and pgbouncer.ini when it is necessary.
### startup-scripts ### startup-scripts
+12
View File
@@ -0,0 +1,12 @@
[template]
prefix = "/service/batman"
owner = "postgres"
mode = "0644"
src = "pgbouncer.tmpl"
dest = "/etc/pgbouncer/pgbouncer.ini"
reload_cmd = "systemctl reload pgbouncer"
keys = [
"/members/","/leader"
]
+17
View File
@@ -0,0 +1,17 @@
[databases]
{{with get "/leader"}}{{$leader := .Value}}{{$leadkey := printf "/members/%s" $leader}}{{with get $leadkey}}{{$data := json .Value}}{{$hostport := base (replace (index (split $data.conn_url "/") 2) "@" "/" -1)}}{{ $host := base (index (split $hostport ":") 0)}}{{ $port := base (index (split $hostport ":") 1)}}* = host={{ $host }} port={{ $port }} pool_size=10{{end}}{{end}}
[pgbouncer]
logfile = /var/log/postgresql/pgbouncer.log
pidfile = /var/run/postgresql/pgbouncer.pid
listen_addr = *
listen_port = 6432
unix_socket_dir = /var/run/postgresql
auth_type = trust
auth_file = /etc/pgbouncer/userlist.txt
auth_hba_file = /etc/pgbouncer/pg_hba.txt
admin_users = pgbouncer
stats_users = pgbouncer
pool_mode = session
max_client_conn = 100
default_pool_size = 20
+15 -1
View File
@@ -11,12 +11,26 @@ Type=simple
User=postgres User=postgres
Group=postgres Group=postgres
# Read in configuration file if it exists, otherwise proceed
EnvironmentFile=-/etc/patroni_env.conf
WorkingDirectory=~
# Where to send early-startup messages from the server # Where to send early-startup messages from the server
# This is normally controlled by the global default set by systemd # This is normally controlled by the global default set by systemd
# StandardOutput=syslog #StandardOutput=syslog
# Pre-commands to start watchdog device
# Uncomment if watchdog is part of your patroni setup
#ExecStartPre=-/usr/bin/sudo /sbin/modprobe softdog
#ExecStartPre=-/usr/bin/sudo /bin/chown postgres /dev/watchdog
# Start the patroni process
ExecStart=/bin/patroni /etc/patroni.yml ExecStart=/bin/patroni /etc/patroni.yml
# Send HUP to reload from patroni.yml
ExecReload=/bin/kill -s HUP $MAINPID
# only kill the patroni process, not it's children, so it will gracefully stop postgres # only kill the patroni process, not it's children, so it will gracefully stop postgres
KillMode=process KillMode=process
+8 -6
View File
@@ -14,11 +14,13 @@ Feature: basic replication
Then table foo is present on postgres2 after 20 seconds Then table foo is present on postgres2 after 20 seconds
Scenario: check restart of sync replica Scenario: check restart of sync replica
Given I run patronictl.py restart batman postgres2 --force Given I shut down postgres2
And "sync" key in DCS has sync_standby=postgres1 after 2 seconds Then "sync" key in DCS has sync_standby=postgres1 after 5 seconds
And I run patronictl.py restart batman postgres1 --force When I start postgres2
Then I receive a response returncode 0 And I shut down postgres1
And "sync" key in DCS has sync_standby=postgres2 after 10 seconds Then "sync" key in DCS has sync_standby=postgres2 after 10 seconds
When I start postgres1
And "members/postgres1" key in DCS has state=running after 10 seconds
And I sleep for 2 seconds And I sleep for 2 seconds
When I issue a GET request to http://127.0.0.1:8010/sync When I issue a GET request to http://127.0.0.1:8010/sync
Then I receive a response code 200 Then I receive a response code 200
@@ -30,7 +32,7 @@ Feature: basic replication
Then I receive a response returncode 0 Then I receive a response returncode 0
When I sleep for 2 seconds When I sleep for 2 seconds
And I shut down postgres0 And I shut down postgres0
And I run patronictl.py resume batman And I run patronictl.py resume batman
Then I receive a response returncode 0 Then I receive a response returncode 0
And postgres2 role is the primary after 24 seconds And postgres2 role is the primary after 24 seconds
When I issue a PATCH request to http://127.0.0.1:8010/config with {"synchronous_mode": null, "master_start_timeout": 0} When I issue a PATCH request to http://127.0.0.1:8010/config with {"synchronous_mode": null, "master_start_timeout": 0}
+5
View File
@@ -0,0 +1,5 @@
#!/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
+42 -20
View File
@@ -12,6 +12,7 @@ import shutil
import signal import signal
import six import six
import subprocess import subprocess
import sys
import tempfile import tempfile
import threading import threading
import time import time
@@ -84,7 +85,7 @@ class AbstractController(object):
class PatroniController(AbstractController): class PatroniController(AbstractController):
__PORT = 5440 __PORT = 5360
PATRONI_CONFIG = '{}.yml' PATRONI_CONFIG = '{}.yml'
""" starts and stops individual patronis""" """ starts and stops individual patronis"""
@@ -110,19 +111,31 @@ class PatroniController(AbstractController):
with open(os.path.join(self._data_dir, 'label'), 'w') as f: with open(os.path.join(self._data_dir, 'label'), 'w') as f:
f.write(content) f.write(content)
def read_label(self): def read_label(self, label):
try: try:
with open(os.path.join(self._data_dir, 'label'), 'r') as f: with open(os.path.join(self._data_dir, label), 'r') as f:
return f.read().strip() return f.read().strip()
except IOError: except IOError:
return None return None
def add_tag_to_config(self, tag, value): @staticmethod
def recursive_update(dst, src):
for k, v in src.items():
if k in dst and isinstance(dst[k], dict):
PatroniController.recursive_update(dst[k], v)
else:
dst[k] = v
def update_config(self, custom_config):
with open(self._config) as r: with open(self._config) as r:
config = yaml.safe_load(r) config = yaml.safe_load(r)
config['tags']['tag'] = value self.recursive_update(config, custom_config)
with open(self._config, 'w') as w: with open(self._config, 'w') as w:
yaml.safe_dump(config, w, default_flow_style=False) yaml.safe_dump(config, w, default_flow_style=False)
self._scope = config.get('scope', 'batman')
def add_tag_to_config(self, tag, value):
self.update_config({'tags': {tag: value}})
def _start(self): def _start(self):
if self.watchdog: if self.watchdog:
@@ -130,7 +143,8 @@ class PatroniController(AbstractController):
if isinstance(self._context.dcs_ctl, KubernetesController): if isinstance(self._context.dcs_ctl, KubernetesController):
self._context.dcs_ctl.create_pod(self._name[8:], self._scope) self._context.dcs_ctl.create_pod(self._name[8:], self._scope)
os.environ['PATRONI_KUBERNETES_POD_IP'] = '10.0.0.' + self._name[-1] os.environ['PATRONI_KUBERNETES_POD_IP'] = '10.0.0.' + self._name[-1]
return subprocess.Popen(['coverage', 'run', '--source=patroni', '-p', 'patroni.py', self._config], return subprocess.Popen([sys.executable, '-m', 'coverage', 'run',
'--source=patroni', '-p', 'patroni.py', self._config],
stdout=self._log, stderr=subprocess.STDOUT, cwd=self._work_directory) stdout=self._log, stderr=subprocess.STDOUT, cwd=self._work_directory)
def stop(self, kill=False, timeout=15, postgres=False): def stop(self, kill=False, timeout=15, postgres=False):
@@ -174,13 +188,10 @@ class PatroniController(AbstractController):
config['bootstrap']['initdb'].extend([{'auth': 'md5'}, {'auth-host': 'md5'}]) config['bootstrap']['initdb'].extend([{'auth': 'md5'}, {'auth-host': 'md5'}])
if custom_config is not None: if custom_config is not None:
def recursive_update(dst, src): self.recursive_update(config, custom_config)
for k, v in src.items():
if k in dst and isinstance(dst[k], dict): if config['postgresql'].get('callbacks', {}).get('on_role_change'):
recursive_update(dst[k], v) config['postgresql']['callbacks']['on_role_change'] += ' ' + str(self.__PORT)
else:
dst[k] = v
recursive_update(config, custom_config)
with open(patroni_config_path, 'w') as f: with open(patroni_config_path, 'w') as f:
yaml.safe_dump(config, f, default_flow_style=False) yaml.safe_dump(config, f, default_flow_style=False)
@@ -287,9 +298,9 @@ 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='basebackup'): def backup(self, dest='data/basebackup'):
subprocess.call([PatroniPoolController.BACKUP_SCRIPT, '--walmethod=none', subprocess.call([PatroniPoolController.BACKUP_SCRIPT, '--walmethod=none',
'--datadir=' + os.path.join(self._output_dir, dest), '--datadir=' + os.path.join(self._work_directory, dest),
'--dbname=' + self.backup_source]) '--dbname=' + self.backup_source])
@@ -363,6 +374,7 @@ class ConsulController(AbstractDcsController):
def __init__(self, context): def __init__(self, context):
super(ConsulController, self).__init__(context) super(ConsulController, self).__init__(context)
os.environ['PATRONI_CONSUL_HOST'] = 'localhost:8500' os.environ['PATRONI_CONSUL_HOST'] = 'localhost:8500'
os.environ['PATRONI_CONSUL_REGISTER_SERVICE'] = 'on'
self._client = consul.Consul() self._client = consul.Consul()
self._config_file = None self._config_file = None
@@ -612,13 +624,20 @@ class PatroniPoolController(object):
'method': 'pg_basebackup', 'method': 'pg_basebackup',
'pg_basebackup': { 'pg_basebackup': {
'command': self.BACKUP_SCRIPT + ' --walmethod=stream --dbname=' + f.backup_source 'command': self.BACKUP_SCRIPT + ' --walmethod=stream --dbname=' + f.backup_source
},
'dcs': {
'postgresql': {
'parameters': {
'max_connections': 101
}
}
} }
}, },
'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': 'mkdir -p {0} && test ! -f {0}/%f && cp %p {0}/%f'.format(
os.path.join(self._output_dir, 'wal_archive')) os.path.join(self.patroni_path, 'data/wal_archive'))
}, },
'authentication': { 'authentication': {
'superuser': {'password': 'zalando1'}, 'superuser': {'password': 'zalando1'},
@@ -634,11 +653,12 @@ 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._output_dir, 'basebackup'), 'command': 'features/backup_restore.sh --sourcedir=' + 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}/wal_archive/%f %p'.format(self._output_dir) 'restore_command': 'cp {0}/data/wal_archive/%f %p'.format(self.patroni_path)
} }
} }
}, },
@@ -792,8 +812,8 @@ def before_all(context):
def after_all(context): def after_all(context):
context.dcs_ctl.stop() context.dcs_ctl.stop()
subprocess.call(['coverage', 'combine']) subprocess.call([sys.executable, '-m', 'coverage', 'combine'])
subprocess.call(['coverage', 'report']) subprocess.call([sys.executable, '-m', 'coverage', 'report'])
def before_feature(context, feature): def before_feature(context, feature):
@@ -806,3 +826,5 @@ def after_feature(context, feature):
context.pctl.stop_all() context.pctl.stop_all()
shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data')) shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data'))
context.dcs_ctl.cleanup_service_tree() context.dcs_ctl.cleanup_service_tree()
if feature.status == 'failed':
shutil.copytree(context.pctl.output_dir, context.pctl.output_dir + '_failed')
+19 -1
View File
@@ -8,6 +8,8 @@ Scenario: check API requests on a stand-alone server
Then I receive a response code 200 Then I receive a response code 200
And I receive a response state running And I receive a response state running
And I receive a response role master And I receive a response role master
When I issue a GET request to http://127.0.0.1:8008/health
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8008/replica When I issue a GET request to http://127.0.0.1:8008/replica
Then I receive a response code 503 Then I receive a response code 503
When I run patronictl.py reinit batman postgres0 --force When I run patronictl.py reinit batman postgres0 --force
@@ -43,7 +45,7 @@ Scenario: check dynamic configuration change via DCS
And I receive a response loop_wait 2 And I receive a response loop_wait 2
When I issue a GET request to http://127.0.0.1:8008/patroni When I issue a GET request to http://127.0.0.1:8008/patroni
Then I receive a response code 200 Then I receive a response code 200
And I receive a response tags {'tag': 'new_value'} And I receive a response tags {'new_tag': 'new_value'}
Scenario: check API requests for the primary-replica pair in the pause mode Scenario: check API requests for the primary-replica pair in the pause mode
Given I run patronictl.py pause batman Given I run patronictl.py pause batman
@@ -71,6 +73,14 @@ Scenario: check the switchover via the API in the pause mode
And postgres1 role is the primary after 10 seconds And postgres1 role is the primary after 10 seconds
And postgres0 role is the secondary after 10 seconds And postgres0 role is the secondary after 10 seconds
And replication works from postgres1 to postgres0 after 20 seconds And replication works from postgres1 to postgres0 after 20 seconds
When I issue a GET request to http://127.0.0.1:8008/master
Then I receive a response code 503
When I issue a GET request to http://127.0.0.1:8008/replica
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8009/master
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8009/replica
Then I receive a response code 503
Scenario: check the scheduled switchover Scenario: check the scheduled switchover
Given I issue a scheduled switchover from postgres1 to postgres0 in 3 seconds Given I issue a scheduled switchover from postgres1 to postgres0 in 3 seconds
@@ -84,6 +94,14 @@ Scenario: check the scheduled switchover
And postgres0 role is the primary after 10 seconds And postgres0 role is the primary after 10 seconds
And postgres1 role is the secondary after 10 seconds And postgres1 role is the secondary after 10 seconds
And replication works from postgres0 to postgres1 after 25 seconds And replication works from postgres0 to postgres1 after 25 seconds
When I issue a GET request to http://127.0.0.1:8008/master
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8008/replica
Then I receive a response code 503
When I issue a GET request to http://127.0.0.1:8009/master
Then I receive a response code 503
When I issue a GET request to http://127.0.0.1:8009/replica
Then I receive a response code 200
Scenario: check the scheduled restart Scenario: check the scheduled restart
Given I issue a PATCH request to http://127.0.0.1:8008/config with {"postgresql": {"parameters": {"superuser_reserved_connections": "6"}}} Given I issue a PATCH request to http://127.0.0.1:8008/config with {"postgresql": {"parameters": {"superuser_reserved_connections": "6"}}}
+48
View File
@@ -0,0 +1,48 @@
Feature: standby cluster
Scenario: check permanent logical slots are preserved on failover/switchover
Given I start postgres1
Then postgres1 is a leader after 10 seconds
And I sleep for 3 seconds
When I issue a PATCH request to http://127.0.0.1:8009/config with {"loop_wait": 2, "slots": {"pm_1": {"type": "physical"}}, "postgresql": {"parameters": {"wal_level": "logical"}}}
Then I receive a response code 200
And Response on GET http://127.0.0.1:8009/config contains slots after 10 seconds
And I sleep for 3 seconds
When I issue a PATCH request to http://127.0.0.1:8009/config with {"slots": {"test_logical": {"type": "logical", "database": "postgres", "plugin": "test_decoding"}}}
Then I receive a response code 200
And I do a backup of postgres1
When I start postgres0 with callback configured
Then "members/postgres0" key in DCS has state=running after 10 seconds
And replication works from postgres1 to postgres0 after 15 seconds
When I shut down postgres1
Then postgres0 is a leader after 10 seconds
And "members/postgres0" key in DCS has role=master after 3 seconds
When I issue a GET request to http://127.0.0.1:8008/
Then I receive a response code 200
And there is a label with "test_logical" in postgres0 data directory
Scenario: check replication of a single table in a standby cluster
Given I start postgres1 in a standby cluster batman1 as a clone of postgres0
Then postgres1 is a leader of batman1 after 10 seconds
When I add the table foo to postgres0
Then table foo is present on postgres1 after 20 seconds
When I issue a GET request to http://127.0.0.1:8009/master
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8009/standby_leader
Then I receive a response code 200
And I receive a response role standby_leader
And there is a postgres1_cb.log with "on_start replica batman1\non_role_change standby_leader batman1" in postgres1 data directory
When I start postgres2 in a cluster batman1
Then postgres2 role is the replica after 24 seconds
And table foo is present on postgres2 after 20 seconds
Scenario: check failover
When I kill postgres1
And I kill postmaster on postgres1
Then postgres2 is replicating from postgres0 after 32 seconds
When I issue a GET request to http://127.0.0.1:8010/master
Then I receive a response code 200
When I issue a GET request to http://127.0.0.1:8010/standby_leader
Then I receive a response code 200
And I receive a response role standby_leader
And replication works from postgres0 to postgres2 after 15 seconds
And there is a postgres2_cb.log with "on_start replica batman1\non_role_change standby_leader batman1" in postgres2 data directory
+4 -3
View File
@@ -9,9 +9,10 @@ def start_patroni_with_a_name_value_tag(context, name, tag_name, tag_value):
return context.pctl.start(name, custom_config={'tags': {tag_name: tag_value}}) return context.pctl.start(name, custom_config={'tags': {tag_name: tag_value}})
@then('There is a label with "{content:w}" in {name:w} data directory') @then('There is a {label} with "{content}" in {name:w} data directory')
def check_label(context, content, name): def check_label(context, label, content, name):
label = context.pctl.read_label(name) label = context.pctl.read_label(name, label)
label = label.replace('\n', '\\n')
assert label == content, "{0} is not equal to {1}".format(label, content) assert label == content, "{0} is not equal to {1}".format(label, content)
+2 -1
View File
@@ -5,6 +5,7 @@ import parse
import requests import requests
import shlex import shlex
import subprocess import subprocess
import sys
import time import time
import yaml import yaml
@@ -95,7 +96,7 @@ def do_request(context, request_method, url, data):
@step('I run {cmd}') @step('I run {cmd}')
def do_run(context, cmd): def do_run(context, cmd):
cmd = ['coverage', 'run', '--source=patroni', '-p'] + shlex.split(cmd) cmd = [sys.executable, '-m', 'coverage', 'run', '--source=patroni', '-p'] + shlex.split(cmd)
try: try:
# XXX: Dirty hack! We need to take name/passwd from the config! # XXX: Dirty hack! We need to take name/passwd from the config!
env = os.environ.copy() env = os.environ.copy()
+82
View File
@@ -0,0 +1,82 @@
import os
import time
from behave import step
select_replication_query = """
SELECT * FROM pg_catalog.pg_stat_replication
WHERE application_name = '{0}'
"""
callback = "bash -c 'echo \"${*: -3:1} ${*: -2:1} ${*: -1:1}\" >> data/$1/$1_cb.log' -- "
@step('I start {name:w} with callback configured')
def start_patroni_with_callbacks(context, name):
return context.pctl.start(name, custom_config={
"postgresql": {
"callbacks": {
"on_role_change": "features/callback.sh"
}
}
})
@step('I start {name:w} in a cluster {cluster_name:w}')
def start_patroni(context, name, cluster_name):
return context.pctl.start(name, custom_config={
"scope": cluster_name,
"postgresql": {
"callbacks": {c: callback + name for c in ('on_start', 'on_stop', 'on_restart', 'on_role_change')},
"backup_restore": {
"command": "features/backup_restore.sh --sourcedir=" + os.path.join(context.pctl.patroni_path,
"data/basebackup")}
}
})
@step('I start {name:w} in a standby cluster {cluster_name:w} as a clone of {name2:w}')
def start_patroni_standby_cluster(context, name, cluster_name, name2):
# we need to remove patroni.dynamic.json in order to "bootstrap" standby cluster with existing PGDATA
os.unlink(os.path.join(context.pctl._processes[name]._data_dir, 'patroni.dynamic.json'))
port = context.pctl._processes[name2]._connkwargs.get('port')
context.pctl._processes[name].update_config({
"scope": cluster_name,
"bootstrap": {
"dcs": {
"ttl": 20,
"loop_wait": 2,
"retry_timeout": 5,
"standby_cluster": {
"host": "localhost",
"port": port,
"primary_slot_name": "pm_1",
"create_replica_methods": ["backup_restore", "basebackup"]
}
}
},
"postgresql": {
"callbacks": {c: callback + name for c in ('on_start', 'on_stop', 'on_restart', 'on_role_change')}
}
})
return context.pctl.start(name)
@step('{pg_name1:w} is replicating from {pg_name2:w} after {timeout:d} seconds')
def check_replication_status(context, pg_name1, pg_name2, timeout):
bound_time = time.time() + timeout
while time.time() < bound_time:
cur = context.pctl.query(
pg_name2,
select_replication_query.format(pg_name1),
fail_ok=True
)
if cur and len(cur.fetchall()) != 0:
break
time.sleep(1)
else:
assert False, "{0} is not replicating from {1} after {2} seconds".format(pg_name1, pg_name2, timeout)
+16 -14
View File
@@ -1,32 +1,34 @@
FROM postgres:9.6 FROM postgres:11
MAINTAINER Alexander Kukushkin <[email protected]> MAINTAINER Alexander Kukushkin <[email protected]>
RUN export DEBIAN_FRONTEND=noninteractive \ RUN export DEBIAN_FRONTEND=noninteractive \
&& echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \ && echo 'APT::Install-Recommends "0";\nAPT::Install-Suggests "0";' > /etc/apt/apt.conf.d/01norecommend \
&& apt-get update -y \ && apt-get update -y \
&& apt-get upgrade -y \ && apt-get upgrade -y \
&& apt-get install -y git curl jq python-psycopg2 python-yaml python-requests python-six python-pysocks \ && apt-cache depends patroni | sed -n -e 's/.* Depends: \(python3-.\+\)$/\1/p' \
python-dateutil python-pip python-prettytable python-wheel python-psutil python locales \ | grep -Ev '^python3-(sphinx|etcd|consul|kazoo|kubernetes)' \
| xargs apt-get install -y vim-tiny curl jq locales git python3-pip python3-wheel \
## Make sure we have a en_US.UTF-8 locale available ## Make sure we have a en_US.UTF-8 locale available
&& localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \ && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8 \
&& pip3 install setuptools \
&& pip install setuptools pip --upgrade \ && pip3 install 'git+https://github.com/zalando/patroni.git#egg=patroni[kubernetes]' \
&& pip install 'git+https://github.com/zalando/patroni.git#egg=patroni[kubernetes]' \ && PGHOME=/home/postgres \
&& mkdir -p $PGHOME \
&& mkdir -p /home/postgres \ && chown postgres $PGHOME \
&& chown postgres:postgres /home/postgres \ && sed -i "s|/var/lib/postgresql.*|$PGHOME:/bin/bash|" /etc/passwd \
# Set permissions for OpenShift
&& chmod 775 $PGHOME \
&& chmod 664 /etc/passwd \
# Clean up # Clean up
&& apt-get remove -y git python-pip python-setuptools \ && apt-get remove -y git python3-pip python3-wheel \
&& apt-get autoremove -y \ && apt-get autoremove -y \
&& apt-get clean -y \ && apt-get clean -y \
&& rm -rf /var/lib/apt/lists/* /root/.cache && rm -rf /var/lib/apt/lists/* /root/.cache
ADD entrypoint.sh callback.py / ADD entrypoint.sh /
EXPOSE 5432 8008 EXPOSE 5432 8008
ENV LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 ENV LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 EDITOR=/usr/bin/editor
USER postgres USER postgres
WORKDIR /home/postgres WORKDIR /home/postgres
CMD ["/bin/bash", "/entrypoint.sh"] CMD ["/bin/bash", "/entrypoint.sh"]
-62
View File
@@ -1,62 +0,0 @@
#!/usr/bin/env python
import logging
import os
import socket
import sys
import time
from kubernetes import client as k8s_client, config as k8s_config
from urllib3.exceptions import HTTPError
from six.moves.http_client import HTTPException
logger = logging.getLogger(__name__)
class CoreV1Api(k8s_client.CoreV1Api):
def retry(func):
def wrapped(*args, **kwargs):
count = 0
while True:
try:
return func(*args, **kwargs)
except (HTTPException, HTTPError, socket.error, socket.timeout):
if count >= 10:
raise
logger.info('Throttling API requests...')
time.sleep(2 ** count * 0.5)
count += 1
return wrapped
@retry
def patch_namespaced_endpoints(self, *args, **kwargs):
return super(CoreV1Api, self).patch_namespaced_endpoints(*args, **kwargs)
def patch_master_endpoint(api, namespace, cluster):
addresses = [k8s_client.V1EndpointAddress(ip=os.environ['POD_IP'])]
ports = [k8s_client.V1EndpointPort(port=5432)]
subsets = [k8s_client.V1EndpointSubset(addresses=addresses, ports=ports)]
body = k8s_client.V1Endpoints(subsets=subsets)
return api.patch_namespaced_endpoints(cluster, namespace, body)
def main():
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO)
if len(sys.argv) != 4 or sys.argv[1] not in ('on_start', 'on_stop', 'on_role_change'):
sys.exit('Usage: %s <action> <role> <cluster_name>', sys.argv[0])
action, role, cluster = sys.argv[1:4]
k8s_config.load_incluster_config()
k8s_api = CoreV1Api()
namespace = os.environ['KUBERNETES_NAMESPACE']
if role == 'master' and action in ('on_start', 'on_role_change'):
patch_master_endpoint(k8s_api, namespace, cluster)
if __name__ == '__main__':
main()
+11 -8
View File
@@ -1,5 +1,12 @@
#!/bin/bash #!/bin/bash
if [[ $UID -ge 10000 ]]; then
GID=$(id -g)
sed -e "s/^postgres:x:[^:]*:[^:]*:/postgres:x:$UID:$GID:/" /etc/passwd > /tmp/passwd
cat /tmp/passwd > /etc/passwd
rm /tmp/passwd
fi
cat > /home/postgres/patroni.yml <<__EOF__ cat > /home/postgres/patroni.yml <<__EOF__
bootstrap: bootstrap:
dcs: dcs:
@@ -13,24 +20,20 @@ bootstrap:
- data-checksums - data-checksums
pg_hba: pg_hba:
- host all all 0.0.0.0/0 md5 - host all all 0.0.0.0/0 md5
- host replication ${PATRONI_REPLICATION_USERNAME} ${POD_IP}/16 md5 - host replication ${PATRONI_REPLICATION_USERNAME} ${PATRONI_KUBERNETES_POD_IP}/16 md5
restapi: restapi:
connect_address: '${POD_IP}:8008' connect_address: '${PATRONI_KUBERNETES_POD_IP}:8008'
postgresql: postgresql:
connect_address: '${POD_IP}:5432' connect_address: '${PATRONI_KUBERNETES_POD_IP}:5432'
authentication: authentication:
superuser: superuser:
password: '${PATRONI_SUPERUSER_PASSWORD}' password: '${PATRONI_SUPERUSER_PASSWORD}'
replication: replication:
password: '${PATRONI_REPLICATION_PASSWORD}' password: '${PATRONI_REPLICATION_PASSWORD}'
callbacks:
on_start: /callback.py
on_stop: /callback.py
on_role_change: /callback.py
__EOF__ __EOF__
unset PATRONI_SUPERUSER_PASSWORD PATRONI_REPLICATION_PASSWORD unset PATRONI_SUPERUSER_PASSWORD PATRONI_REPLICATION_PASSWORD
export KUBERNETES_NAMESPACE=$PATRONI_KUBERNETES_NAMESPACE export KUBERNETES_NAMESPACE=$PATRONI_KUBERNETES_NAMESPACE
export POD_NAME=$PATRONI_NAME export POD_NAME=$PATRONI_NAME
exec /usr/bin/python /usr/local/bin/patroni /home/postgres/patroni.yml exec /usr/bin/python3 /usr/local/bin/patroni /home/postgres/patroni.yml
+49
View File
@@ -0,0 +1,49 @@
# Patroni OpenShift Configuration
Patroni can be run in OpenShift. Based on the kubernetes configuration, the Dockerfile and Entrypoint has been modified to support the dynamic UID/GID configuration that is applied in OpenShift. This can be run under the standard `restricted` SCC.
# Examples
## Create test project
```
oc new-project patroni-test
```
## Build the image
Note: Update the references when merged upstream.
Note: If deploying as a template for multiple users, the following commands should be performed in a shared namespace like `openshift`.
```
oc import-image postgres:10 --confirm -n openshift
oc new-build https://github.com/zalando/patroni --context-dir=kubernetes -n openshift
```
## Deploy the Image
Two configuration templates exist in [templates](templates) directory:
- Patroni Ephemeral
- Patroni Persistent
The only difference is whether or not the statefulset requests persistent storage.
## Create the Template
Install the template into the `openshift` namespace if this should be shared across projects:
```
oc create -f templates/template_patroni_ephemeral.yml -n openshift
```
Then, from your own project:
```
oc new-app patroni-pgsql-ephemeral
```
Once the pods are running, two configmaps should be available:
```
$ oc get configmap
NAME DATA AGE
patroniocp-config 0 1m
patroniocp-leader 0 1m
```
@@ -0,0 +1,287 @@
apiVersion: v1
kind: Template
metadata:
name: patroni-pgsql-ephemeral
annotations:
description: |-
Patroni Postgresql database cluster, without persistent storage.
WARNING: Any data stored will be lost upon pod destruction. Only use this template for testing.
iconClass: icon-postgresql
openshift.io/display-name: Patroni Postgresql (Ephemeral)
openshift.io/long-description: This template deploys a a patroni postgresql HA cluster without persistent storage.
tags: postgresql
objects:
- apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${PATRONI_CLUSTER_NAME}
spec:
ports:
- port: 5432
protocol: TCP
targetPort: 5432
sessionAffinity: None
type: ClusterIP
status:
loadBalancer: {}
- apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${PATRONI_MASTER_SERVICE_NAME}
spec:
ports:
- port: 5432
protocol: TCP
targetPort: 5432
selector:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
role: master
sessionAffinity: None
type: ClusterIP
status:
loadBalancer: {}
- apiVersion: v1
kind: Secret
metadata:
name: ${PATRONI_CLUSTER_NAME}
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
stringData:
superuser-password: ${PATRONI_SUPERUSER_PASSWORD}
replication-password: ${PATRONI_REPLICATION_PASSWORD}
- apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${PATRONI_REPLICA_SERVICE_NAME}
spec:
ports:
- port: 5432
protocol: TCP
targetPort: 5432
selector:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
role: replica
sessionAffinity: None
type: ClusterIP
status:
loadBalancer: {}
- apiVersion: apps/v1
kind: StatefulSet
metadata:
creationTimestamp: null
generation: 3
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${APPLICATION_NAME}
spec:
podManagementPolicy: OrderedReady
replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
serviceName: ${APPLICATION_NAME}
template:
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
spec:
containers:
- env:
- name: PATRONI_KUBERNETES_POD_IP
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: status.podIP
- name: PATRONI_KUBERNETES_NAMESPACE
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
- name: PATRONI_KUBERNETES_LABELS
value: '{application: ${APPLICATION_NAME}, cluster-name: ${PATRONI_CLUSTER_NAME}}'
- name: PATRONI_SUPERUSER_USERNAME
value: ${PATRONI_SUPERUSER_USERNAME}
- name: PATRONI_SUPERUSER_PASSWORD
valueFrom:
secretKeyRef:
key: superuser-password
name: ${PATRONI_CLUSTER_NAME}
- name: PATRONI_REPLICATION_USERNAME
value: ${PATRONI_REPLICATION_USERNAME}
- name: PATRONI_REPLICATION_PASSWORD
valueFrom:
secretKeyRef:
key: replication-password
name: ${PATRONI_CLUSTER_NAME}
- name: PATRONI_SCOPE
value: ${PATRONI_CLUSTER_NAME}
- name: PATRONI_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
- name: PATRONI_POSTGRESQL_DATA_DIR
value: /home/postgres/pgdata/pgroot/data
- name: PATRONI_POSTGRESQL_PGPASS
value: /tmp/pgpass
- name: PATRONI_POSTGRESQL_LISTEN
value: 0.0.0.0:5432
- name: PATRONI_RESTAPI_LISTEN
value: 0.0.0.0:8008
image: docker-registry.default.svc:5000/${NAMESPACE}/patroni:latest
imagePullPolicy: IfNotPresent
name: ${APPLICATION_NAME}
ports:
- containerPort: 8008
protocol: TCP
- containerPort: 5432
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /home/postgres/pgdata
name: pgdata
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: ${SERVICE_ACCOUNT}
serviceAccountName: ${SERVICE_ACCOUNT}
terminationGracePeriodSeconds: 0
volumes:
- name: pgdata
emptyDir: {}
updateStrategy:
type: OnDelete
- apiVersion: v1
kind: Endpoints
metadata:
name: ${APPLICATION_NAME}
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
subsets: []
- apiVersion: v1
kind: ServiceAccount
metadata:
name: ${SERVICE_ACCOUNT}
- apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: ${SERVICE_ACCOUNT}
rules:
- apiGroups:
- ""
resources:
- configmaps
verbs:
- create
- get
- list
- patch
- update
- watch
# delete is required only for 'patronictl remove'
- delete
- apiGroups:
- ""
resources:
- endpoints
verbs:
- get
- patch
- update
# the following three privileges are necessary only when using endpoints
- create
- list
- watch
# delete is required only for for 'patronictl remove'
- delete
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
- patch
- update
- watch
- apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: ${SERVICE_ACCOUNT}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: ${SERVICE_ACCOUNT}
subjects:
- kind: ServiceAccount
name: ${SERVICE_ACCOUNT}
parameters:
- description: The name of the application for labelling all artifacts.
displayName: Application Name
name: APPLICATION_NAME
value: patroni-ephemeral
- description: The name of the patroni-pgsql cluster.
displayName: Cluster Name
name: PATRONI_CLUSTER_NAME
value: patroni-ephemeral
- description: The name of the OpenShift Service exposed for the patroni-ephemeral-master container.
displayName: Master service name.
name: PATRONI_MASTER_SERVICE_NAME
value: patroni-ephemeral-master
- description: The name of the OpenShift Service exposed for the patroni-ephemeral-replica containers.
displayName: Replica service name.
name: PATRONI_REPLICA_SERVICE_NAME
value: patroni-ephemeral-replica
- description: Maximum amount of memory the container can use.
displayName: Memory Limit
name: MEMORY_LIMIT
value: 512Mi
- description: The OpenShift Namespace where the patroni and postgresql ImageStream resides.
displayName: ImageStream Namespace
name: NAMESPACE
value: openshift
- description: Username of the superuser account for initialization.
displayName: Superuser Username
name: PATRONI_SUPERUSER_USERNAME
value: postgres
- description: Password of the superuser account for initialization.
displayName: Superuser Passsword
name: PATRONI_SUPERUSER_PASSWORD
value: postgres
- description: Username of the replication account for initialization.
displayName: Replication Username
name: PATRONI_REPLICATION_USERNAME
value: postgres
- description: Password of the replication account for initialization.
displayName: Repication Passsword
name: PATRONI_REPLICATION_PASSWORD
value: postgres
- description: Service account name used for pods and rolebindings to form a cluster in the project.
displayName: Service Account
name: SERVICE_ACCOUNT
value: patroniocp
@@ -0,0 +1,303 @@
apiVersion: v1
kind: Template
metadata:
name: patroni-pgsql-persistent
annotations:
description: |-
Patroni Postgresql database cluster, with persistent storage.
WARNING: Any data stored will be lost upon pod destruction. Only use this template for testing.
iconClass: icon-postgresql
openshift.io/display-name: Patroni Postgresql (Persistent)
openshift.io/long-description: This template deploys a a patroni postgresql HA cluster without persistent storage.
tags: postgresql
objects:
- apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${PATRONI_CLUSTER_NAME}
spec:
ports:
- port: 5432
protocol: TCP
targetPort: 5432
sessionAffinity: None
type: ClusterIP
status:
loadBalancer: {}
- apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${PATRONI_MASTER_SERVICE_NAME}
spec:
ports:
- port: 5432
protocol: TCP
targetPort: 5432
selector:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
role: master
sessionAffinity: None
type: ClusterIP
status:
loadBalancer: {}
- apiVersion: v1
kind: Secret
metadata:
name: ${PATRONI_CLUSTER_NAME}
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
stringData:
superuser-password: ${PATRONI_SUPERUSER_PASSWORD}
replication-password: ${PATRONI_REPLICATION_PASSWORD}
- apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${PATRONI_REPLICA_SERVICE_NAME}
spec:
ports:
- port: 5432
protocol: TCP
targetPort: 5432
selector:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
role: replica
sessionAffinity: None
type: ClusterIP
status:
loadBalancer: {}
- apiVersion: apps/v1
kind: StatefulSet
metadata:
creationTimestamp: null
generation: 3
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
name: ${APPLICATION_NAME}
spec:
podManagementPolicy: OrderedReady
replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
serviceName: ${APPLICATION_NAME}
template:
metadata:
creationTimestamp: null
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
spec:
containers:
- env:
- name: PATRONI_KUBERNETES_POD_IP
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: status.podIP
- name: PATRONI_KUBERNETES_NAMESPACE
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
- name: PATRONI_KUBERNETES_LABELS
value: '{application: ${APPLICATION_NAME}, cluster-name: ${PATRONI_CLUSTER_NAME}}'
- name: PATRONI_SUPERUSER_USERNAME
value: ${PATRONI_SUPERUSER_USERNAME}
- name: PATRONI_SUPERUSER_PASSWORD
valueFrom:
secretKeyRef:
key: superuser-password
name: ${PATRONI_CLUSTER_NAME}
- name: PATRONI_REPLICATION_USERNAME
value: ${PATRONI_REPLICATION_USERNAME}
- name: PATRONI_REPLICATION_PASSWORD
valueFrom:
secretKeyRef:
key: replication-password
name: ${PATRONI_CLUSTER_NAME}
- name: PATRONI_SCOPE
value: ${PATRONI_CLUSTER_NAME}
- name: PATRONI_NAME
valueFrom:
fieldRef:
apiVersion: v1
fieldPath: metadata.name
- name: PATRONI_POSTGRESQL_DATA_DIR
value: /home/postgres/pgdata/pgroot/data
- name: PATRONI_POSTGRESQL_PGPASS
value: /tmp/pgpass
- name: PATRONI_POSTGRESQL_LISTEN
value: 0.0.0.0:5432
- name: PATRONI_RESTAPI_LISTEN
value: 0.0.0.0:8008
image: docker-registry.default.svc:5000/${NAMESPACE}/patroni:latest
imagePullPolicy: IfNotPresent
name: ${APPLICATION_NAME}
ports:
- containerPort: 8008
protocol: TCP
- containerPort: 5432
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /home/postgres/pgdata
name: ${APPLICATION_NAME}
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: ${SERVICE_ACCOUNT}
serviceAccountName: ${SERVICE_ACCOUNT}
terminationGracePeriodSeconds: 0
volumes:
- name: ${APPLICATION_NAME}
persistentVolumeClaim:
claimName: ${APPLICATION_NAME}
volumeClaimTemplates:
- metadata:
labels:
application: ${APPLICATION_NAME}
name: ${APPLICATION_NAME}
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: ${PVC_SIZE}
updateStrategy:
type: OnDelete
- apiVersion: v1
kind: Endpoints
metadata:
name: ${APPLICATION_NAME}
labels:
application: ${APPLICATION_NAME}
cluster-name: ${PATRONI_CLUSTER_NAME}
subsets: []
- apiVersion: v1
kind: ServiceAccount
metadata:
name: ${SERVICE_ACCOUNT}
- apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: ${SERVICE_ACCOUNT}
rules:
- apiGroups:
- ""
resources:
- configmaps
verbs:
- create
- get
- list
- patch
- update
- watch
# delete is required only for 'patronictl remove'
- delete
- apiGroups:
- ""
resources:
- endpoints
verbs:
- get
- patch
- update
# the following three privileges are necessary only when using endpoints
- create
- list
- watch
# delete is required only for for 'patronictl remove'
- delete
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
- patch
- update
- watch
- apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: ${SERVICE_ACCOUNT}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: ${SERVICE_ACCOUNT}
subjects:
- kind: ServiceAccount
name: ${SERVICE_ACCOUNT}
parameters:
- description: The name of the application for labelling all artifacts.
displayName: Application Name
name: APPLICATION_NAME
value: patroni-persistent
- description: The name of the patroni-pgsql cluster.
displayName: Cluster Name
name: PATRONI_CLUSTER_NAME
value: patroni-persistent
- description: The name of the OpenShift Service exposed for the patroni-persistent-master container.
displayName: Master service name.
name: PATRONI_MASTER_SERVICE_NAME
value: patroni-persistent-master
- description: The name of the OpenShift Service exposed for the patroni-persistent-replica containers.
displayName: Replica service name.
name: PATRONI_REPLICA_SERVICE_NAME
value: patroni-persistent-replica
- description: Maximum amount of memory the container can use.
displayName: Memory Limit
name: MEMORY_LIMIT
value: 512Mi
- description: The OpenShift Namespace where the patroni and postgresql ImageStream resides.
displayName: ImageStream Namespace
name: NAMESPACE
value: openshift
- description: Username of the superuser account for initialization.
displayName: Superuser Username
name: PATRONI_SUPERUSER_USERNAME
value: postgres
- description: Password of the superuser account for initialization.
displayName: Superuser Passsword
name: PATRONI_SUPERUSER_PASSWORD
value: postgres
- description: Username of the replication account for initialization.
displayName: Replication Username
name: PATRONI_REPLICATION_USERNAME
value: postgres
- description: Password of the replication account for initialization.
displayName: Repication Passsword
name: PATRONI_REPLICATION_PASSWORD
value: postgres
- description: Service account name used for pods and rolebindings to form a cluster in the project.
displayName: Service Account
name: SERVICE_ACCOUNT
value: patroni-persistent
- description: The size of the persistent volume to create.
displayName: Persistent Volume Size
name: PVC_SIZE
value: 5Gi
+43
View File
@@ -0,0 +1,43 @@
pipeline {
agent any
stages {
stage ('Deploy test pod'){
when {
expression {
openshift.withCluster() {
openshift.withProject() {
return !openshift.selector( "dc", "pgbench" ).exists()
}
}
}
}
steps {
script {
openshift.withCluster() {
openshift.withProject() {
def pgbench = openshift.newApp( "https://github.com/stewartshea/docker-pgbench/", "--name=pgbench", "-e PGPASSWORD=postgres", "-e PGUSER=postgres", "-e PGHOST=patroni-persistent-master", "-e PGDATABASE=postgres", "-e TEST_CLIENT_COUNT=20", "-e TEST_DURATION=120" )
def pgbenchdc = openshift.selector( "dc", "pgbench" )
timeout(5) {
pgbenchdc.rollout().status()
}
}
}
}
}
}
stage ('Run benchmark Test'){
steps {
sh '''
oc exec $(oc get pods -l app=pgbench | grep Running | awk '{print $1}') ./test.sh
'''
}
}
stage ('Clean up pgtest pod'){
steps {
sh '''
oc delete all -l app=pgbench
'''
}
}
}
}
@@ -0,0 +1,2 @@
# Jenkins Test
This pipeline test will create a separate deployment config for a pgbench pod and execute a test against the patroni cluster. This is a sample and should be customized.
+31 -1
View File
@@ -1,3 +1,15 @@
# headless service to avoid deletion of patronidemo-config endpoint
apiVersion: v1
kind: Service
metadata:
name: patronidemo-config
labels:
application: patroni
cluster-name: patronidemo
spec:
clusterIP: None
---
apiVersion: apps/v1beta1 apiVersion: apps/v1beta1
kind: StatefulSet kind: StatefulSet
metadata: metadata:
@@ -28,7 +40,7 @@ spec:
- mountPath: /home/postgres/pgdata - mountPath: /home/postgres/pgdata
name: pgdata name: pgdata
env: env:
- name: POD_IP - name: PATRONI_KUBERNETES_POD_IP
valueFrom: valueFrom:
fieldRef: fieldRef:
fieldPath: status.podIP fieldPath: status.podIP
@@ -36,6 +48,8 @@ spec:
valueFrom: valueFrom:
fieldRef: fieldRef:
fieldPath: metadata.namespace fieldPath: metadata.namespace
- name: PATRONI_KUBERNETES_USE_ENDPOINTS
value: 'true'
- name: PATRONI_KUBERNETES_LABELS - name: PATRONI_KUBERNETES_LABELS
value: '{application: patroni, cluster-name: patronidemo}' value: '{application: patroni, cluster-name: patronidemo}'
- name: PATRONI_SUPERUSER_USERNAME - name: PATRONI_SUPERUSER_USERNAME
@@ -145,6 +159,9 @@ rules:
- patch - patch
- update - update
- watch - watch
# delete and deletecollection are required only for 'patronictl remove'
- delete
- deletecollection
- apiGroups: - apiGroups:
- "" - ""
resources: resources:
@@ -157,6 +174,9 @@ rules:
- create - create
- list - list
- watch - watch
# delete and deletecollection are required only for for 'patronictl remove'
- delete
- deletecollection
- apiGroups: - apiGroups:
- "" - ""
resources: resources:
@@ -167,6 +187,16 @@ rules:
- patch - patch
- update - update
- watch - watch
# The following privilege is only necessary for creation of headless service
# for patronidemo-config endpoint, in order to prevent cleaning it up by the
# k8s master. You can avoid giving this privilege by explicitly creating the
# service like it is done in this manifest (lines 2..10)
- apiGroups:
- ""
resources:
- services
verbs:
- create
--- ---
apiVersion: rbac.authorization.k8s.io/v1 apiVersion: rbac.authorization.k8s.io/v1
+8
View File
@@ -1,6 +1,14 @@
#!/usr/bin/env python #!/usr/bin/env python
from patroni import main from patroni import main
import os
if __name__ == '__main__': if __name__ == '__main__':
if os.getenv("PATRONI_DEBUG_MODE"):
# XXX Visual Code specific https://github.com/microsoft/ptvsd/issues/1443
# create processes by spawning new Python interpreters instead of forking the current one
import multiprocessing
multiprocessing.set_start_method('spawn', True)
main() main()
+65 -36
View File
@@ -14,6 +14,7 @@ class Patroni(object):
from patroni.config import Config from patroni.config import Config
from patroni.dcs import get_dcs from patroni.dcs import get_dcs
from patroni.ha import Ha from patroni.ha import Ha
from patroni.log import PatroniLogger
from patroni.postgresql import Postgresql from patroni.postgresql import Postgresql
from patroni.version import __version__ from patroni.version import __version__
from patroni.watchdog import Watchdog from patroni.watchdog import Watchdog
@@ -21,7 +22,9 @@ class Patroni(object):
self.setup_signal_handlers() self.setup_signal_handlers()
self.version = __version__ self.version = __version__
self.logger = PatroniLogger()
self.config = Config() self.config = Config()
self.logger.reload_config(self.config.get('log', {}))
self.dcs = get_dcs(self.config) self.dcs = get_dcs(self.config)
self.watchdog = Watchdog(self.config) self.watchdog = Watchdog(self.config)
self.load_dynamic_configuration() self.load_dynamic_configuration()
@@ -29,6 +32,7 @@ class Patroni(object):
self.postgresql = Postgresql(self.config['postgresql']) self.postgresql = Postgresql(self.config['postgresql'])
self.api = RestApiServer(self, self.config['restapi']) self.api = RestApiServer(self, self.config['restapi'])
self.ha = Ha(self) self.ha = Ha(self)
self.is_in_debug_mode = bool(os.getenv("PATRONI_DEBUG_MODE"))
self.tags = self.get_tags() self.tags = self.get_tags()
self.next_run = time.time() self.next_run = time.time()
@@ -49,6 +53,7 @@ class Patroni(object):
break break
except DCSError: except DCSError:
logger.warning('Can not get cluster from dcs') logger.warning('Can not get cluster from dcs')
time.sleep(5)
def get_tags(self): def get_tags(self):
return {tag: value for tag, value in self.config.get('tags', {}).items() return {tag: value for tag, value in self.config.get('tags', {}).items()
@@ -65,6 +70,7 @@ class Patroni(object):
def reload_config(self): def reload_config(self):
try: try:
self.tags = self.get_tags() self.tags = self.get_tags()
self.logger.reload_config(self.config.get('log', {}))
self.dcs.reload_config(self.config) self.dcs.reload_config(self.config)
self.watchdog.reload_config(self.config) self.watchdog.reload_config(self.config)
self.api.reload_config(self.config['restapi']) self.api.reload_config(self.config['restapi'])
@@ -80,9 +86,10 @@ class Patroni(object):
self._received_sighup = True self._received_sighup = True
def sigterm_handler(self, *args): def sigterm_handler(self, *args):
if not self._received_sigterm: with self._sigterm_lock:
self._received_sigterm = True if not self._received_sigterm:
sys.exit() self._received_sigterm = True
sys.exit()
@property @property
def noloadbalance(self): def noloadbalance(self):
@@ -96,16 +103,22 @@ class Patroni(object):
self.next_run = current_time self.next_run = current_time
# Release the GIL so we don't starve anyone waiting on async_executor lock # Release the GIL so we don't starve anyone waiting on async_executor lock
time.sleep(0.001) time.sleep(0.001)
# Warn user that Patroni is not keeping up # Warn user that Patroni is not keeping up or runs in debug
logger.warning("Loop time exceeded, rescheduling immediately.") msg = "Patroni runs in the debug mode: keys' TTL is infinite, loop wait disabled" if self.is_in_debug_mode else "Loop time exceeded, rescheduling immediately."
logger.warning(msg)
elif self.ha.watch(nap_time): elif self.ha.watch(nap_time):
self.next_run = time.time() self.next_run = time.time()
@property
def received_sigterm(self):
with self._sigterm_lock:
return self._received_sigterm
def run(self): def run(self):
self.api.start() self.api.start()
self.next_run = time.time() self.next_run = time.time()
while not self._received_sigterm: while not self.received_sigterm:
if self._received_sighup: if self._received_sighup:
self._received_sighup = False self._received_sighup = False
if self.config.reload_local_configuration(): if self.config.reload_local_configuration():
@@ -123,21 +136,27 @@ class Patroni(object):
self.schedule_next_run() self.schedule_next_run()
def setup_signal_handlers(self): def setup_signal_handlers(self):
from threading import Lock
self._received_sighup = False self._received_sighup = False
self._sigterm_lock = Lock()
self._received_sigterm = False self._received_sigterm = False
signal.signal(signal.SIGHUP, self.sighup_handler) if os.name != 'nt':
signal.signal(signal.SIGHUP, self.sighup_handler)
signal.signal(signal.SIGTERM, self.sigterm_handler) signal.signal(signal.SIGTERM, self.sigterm_handler)
def shutdown(self): def shutdown(self):
self.api.shutdown() with self._sigterm_lock:
self._received_sigterm = True
try:
self.api.shutdown()
except Exception:
logger.exception('Exception during RestApi.shutdown')
self.ha.shutdown() self.ha.shutdown()
self.logger.shutdown()
def patroni_main(): def patroni_main():
logformat = os.environ.get('PATRONI_LOGFORMAT', '%(asctime)s %(levelname)s: %(message)s')
logging.basicConfig(format=logformat, level=logging.INFO)
logging.getLogger('requests').setLevel(logging.WARNING)
patroni = Patroni() patroni = Patroni()
try: try:
patroni.run() patroni.run()
@@ -147,32 +166,38 @@ def patroni_main():
patroni.shutdown() patroni.shutdown()
def pg_ctl_start(args): def fatal(string, *args):
import subprocess sys.stderr.write('FATAL: ' + string.format(*args) + '\n')
postmaster = subprocess.Popen(args) sys.exit(1)
print(postmaster.pid)
def call_self(args, **kwargs): def check_psycopg2():
"""This function executes Patroni once again with provided arguments. min_psycopg2 = (2, 5, 4)
min_psycopg2_str = '.'.join(map(str, min_psycopg2))
:args: list of arguments to call Patroni with. def parse_version(version):
:returns: `Popen` object""" for e in version.split('.'):
try:
yield int(e)
except ValueError:
break
exe = [sys.executable] try:
if not getattr(sys, 'frozen', False): # Binary distribution? import psycopg2
exe.append(sys.argv[0]) version_str = psycopg2.__version__.split(' ')[0]
version = tuple(parse_version(version_str))
import subprocess if version < min_psycopg2:
return subprocess.Popen(exe + args, **kwargs) fatal('Patroni requires psycopg2>={0}, but only {1} is available', min_psycopg2_str, version_str)
except ImportError:
fatal('Patroni requires psycopg2>={0} or psycopg2-binary', min_psycopg2_str)
def main(): def main():
check_psycopg2()
if os.getpid() != 1: if os.getpid() != 1:
if len(sys.argv) > 5 and sys.argv[1] == 'pg_ctl_start':
return pg_ctl_start(sys.argv[2:])
return patroni_main() return patroni_main()
# Patroni started with PID=1, it looks like we are in the container
pid = 0 pid = 0
# Looks like we are in a docker, so we will act like init # Looks like we are in a docker, so we will act like init
@@ -183,7 +208,7 @@ def main():
if ret == (0, 0): if ret == (0, 0):
break break
elif ret[0] != pid: elif ret[0] != pid:
logging.info('Reaped pid=%s, exit status=%s', *ret) logger.info('Reaped pid=%s, exit status=%s', *ret)
except OSError: except OSError:
pass pass
@@ -191,14 +216,18 @@ def main():
if pid: if pid:
os.kill(pid, signo) os.kill(pid, signo)
signal.signal(signal.SIGCHLD, sigchld_handler) if os.name != 'nt':
signal.signal(signal.SIGHUP, passtochild) signal.signal(signal.SIGCHLD, sigchld_handler)
signal.signal(signal.SIGHUP, passtochild)
signal.signal(signal.SIGQUIT, passtochild)
signal.signal(signal.SIGUSR1, passtochild)
signal.signal(signal.SIGUSR2, passtochild)
signal.signal(signal.SIGINT, passtochild) signal.signal(signal.SIGINT, passtochild)
signal.signal(signal.SIGUSR1, passtochild) signal.signal(signal.SIGABRT, passtochild)
signal.signal(signal.SIGUSR2, passtochild)
signal.signal(signal.SIGQUIT, passtochild)
signal.signal(signal.SIGTERM, passtochild) signal.signal(signal.SIGTERM, passtochild)
patroni = call_self(sys.argv[1:]) import multiprocessing
patroni = multiprocessing.Process(target=patroni_main)
patroni.start()
pid = patroni.pid pid = patroni.pid
patroni.wait() patroni.join()
+137 -67
View File
@@ -1,14 +1,18 @@
import base64 import base64
import fcntl
import json import json
import logging import logging
import psycopg2 import psycopg2
import time import time
import traceback
import dateutil.parser import dateutil.parser
import datetime import datetime
import os
import socket
from patroni.postgresql import PostgresConnectionException, PostgresException, Postgresql from patroni.postgresql import PostgresConnectionException
from patroni.utils import deep_compare, parse_bool, patch_config, Retry, RetryFailedError, parse_int, tzutc from patroni.postgresql.misc import postgres_version_to_int, PostgresException
from patroni.utils import deep_compare, parse_bool, patch_config, Retry, \
RetryFailedError, parse_int, split_host_port, tzutc, uri
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from six.moves.socketserver import ThreadingMixIn from six.moves.socketserver import ThreadingMixIn
from threading import Thread from threading import Thread
@@ -72,46 +76,52 @@ class RestApiHandler(BaseHTTPRequestHandler):
response['watchdog_failed'] = True response['watchdog_failed'] = True
if patroni.ha.is_paused(): if patroni.ha.is_paused():
response['pause'] = True response['pause'] = True
qsize = patroni.logger.queue_size
if qsize > patroni.logger.NORMAL_LOG_QUEUE_SIZE:
response['logger_queue_size'] = qsize
lost = patroni.logger.records_lost
if lost:
response['logger_records_lost'] = lost
self._write_json_response(status_code, response) self._write_json_response(status_code, response)
def do_GET(self, write_status_code_only=False): def do_GET(self, write_status_code_only=False):
"""Default method for processing all GET requests which can not be routed to other methods""" """Default method for processing all GET requests which can not be routed to other methods"""
time_start = time.time()
request_type = 'OPTIONS' if write_status_code_only else 'GET'
path = '/master' if self.path == '/' else self.path path = '/master' if self.path == '/' else self.path
response = self.get_postgresql_status() response = self.get_postgresql_status()
patroni = self.server.patroni patroni = self.server.patroni
cluster = patroni.dcs.cluster cluster = patroni.dcs.cluster
def is_synchronous(): if not cluster and patroni.ha.is_paused():
return (cluster.is_synchronous_mode() and cluster.sync primary_status_code = 200 if response['role'] == 'master' else 503
and cluster.sync.sync_standby == patroni.postgresql.name)
def is_balanceable_replica():
return response.get('role') == 'replica' and not patroni.noloadbalance
if cluster: # dcs available
if cluster.leader and cluster.leader.name == patroni.postgresql.name: # is_leader
status_code = 200 if 'master' in path else 503
elif 'role' not in response:
status_code = 503
elif response['role'] == 'master': # running as master but without leader lock!!!!
status_code = 503
elif path in ('/sync', '/synchronous'):
status_code = 200 if is_balanceable_replica() and is_synchronous() else 503
elif path in ('/async', '/asynchronous'):
status_code = 200 if is_balanceable_replica() and not is_synchronous() else 503
elif response['role'] in path: # response['role'] != 'master'
status_code = 503 if patroni.noloadbalance else 200
else:
status_code = 503
elif 'role' in response and response['role'] in path:
status_code = 503 if response['role'] != 'master' and patroni.noloadbalance else 200
elif patroni.ha.restart_scheduled() and patroni.postgresql.role == 'master' and 'master' in path:
# exceptional case for master node when the postgres is being restarted via API
status_code = 200
else: else:
status_code = 503 primary_status_code = 200 if patroni.ha.is_leader() else 503
replica_status_code = 200 if not patroni.noloadbalance and \
response.get('role') == 'replica' and response.get('state') == 'running' else 503
status_code = 503
if patroni.ha.is_standby_cluster() and ('standby_leader' in path or 'standby-leader' in path):
status_code = 200 if patroni.ha.is_leader() else 503
elif 'master' in path or 'leader' in path or 'primary' in path or 'read-write' in path:
status_code = primary_status_code
elif 'replica' in path:
status_code = replica_status_code
elif 'read-only' in path:
status_code = 200 if primary_status_code == 200 else replica_status_code
elif 'health' in path:
status_code = 200 if response.get('state') == 'running' else 503
elif cluster: # dcs is available
is_synchronous = cluster.is_synchronous_mode() and cluster.sync \
and cluster.sync.sync_standby == patroni.postgresql.name
if path in ('/sync', '/synchronous') and is_synchronous:
status_code = replica_status_code
elif path in ('/async', '/asynchronous') and not is_synchronous:
status_code = replica_status_code
if write_status_code_only: # when haproxy sends OPTIONS request it reads only status code and nothing more if write_status_code_only: # when haproxy sends OPTIONS request it reads only status code and nothing more
message = self.responses[status_code][0] message = self.responses[status_code][0]
@@ -119,6 +129,10 @@ class RestApiHandler(BaseHTTPRequestHandler):
else: else:
self._write_status_response(status_code, response) self._write_status_response(status_code, response)
time_end = time.time()
self.log_message('%s %s %s latency: %s ms', request_type, path,
status_code, (time_end - time_start) * 1000)
def do_OPTIONS(self): def do_OPTIONS(self):
self.do_GET(write_status_code_only=True) self.do_GET(write_status_code_only=True)
@@ -236,7 +250,7 @@ class RestApiHandler(BaseHTTPRequestHandler):
break break
elif k == 'postgres_version': elif k == 'postgres_version':
try: try:
Postgresql.postgres_version_to_int(request[k]) postgres_version_to_int(request[k])
except PostgresException as e: except PostgresException as e:
status_code = 400 status_code = 400
data = e.value data = e.value
@@ -295,22 +309,23 @@ class RestApiHandler(BaseHTTPRequestHandler):
status_code = 503 status_code = 503
self._write_response(status_code, data) self._write_response(status_code, data)
def poll_failover_result(self, leader, candidate): def poll_failover_result(self, leader, candidate, action):
timeout = max(10, self.server.patroni.dcs.loop_wait) timeout = max(10, self.server.patroni.dcs.loop_wait)
for _ in range(0, timeout*2): for _ in range(0, timeout*2):
time.sleep(1) time.sleep(1)
try: try:
cluster = self.server.patroni.dcs.get_cluster() cluster = self.server.patroni.dcs.get_cluster()
if cluster.leader and cluster.leader.name != leader: if not cluster.is_unlocked() and cluster.leader.name != leader:
if not candidate or candidate == cluster.leader.name: if not candidate or candidate == cluster.leader.name:
return 200, 'Successfully failed over to "{0}"'.format(cluster.leader.name) return 200, 'Successfully {0}ed over to "{1}"'.format(action[:-4], cluster.leader.name)
else: else:
return 200, 'Failed over to "{0}" instead of "{1}"'.format(cluster.leader.name, candidate) return 200, '{0}ed over to "{1}" instead of "{2}"'.format(action[:-4].title(),
cluster.leader.name, candidate)
if not cluster.failover: if not cluster.failover:
return 503, 'Failover failed' return 503, action.title() + ' failed'
except Exception as e: except Exception as e:
logger.debug('Exception occured during polling failover result: %s', e) logger.debug('Exception occured during polling %s result: %s', action, e)
return 503, 'Failover status unknown' return 503, action.title() + ' status unknown'
def is_failover_possible(self, cluster, leader, candidate, action): def is_failover_possible(self, cluster, leader, candidate, action):
if leader and (not cluster.leader or cluster.leader.name != leader): if leader and (not cluster.leader or cluster.leader.name != leader):
@@ -377,7 +392,8 @@ class RestApiHandler(BaseHTTPRequestHandler):
data = action.title() + ' scheduled' data = action.title() + ' scheduled'
status_code = 202 status_code = 202
else: else:
status_code, data = self.poll_failover_result(cluster.leader and cluster.leader.name, candidate) status_code, data = self.poll_failover_result(cluster.leader and cluster.leader.name,
candidate, action)
else: else:
data = 'failed to write {0} key into DCS'.format(action) data = 'failed to write {0} key into DCS'.format(action)
status_code = 503 status_code = 503
@@ -412,21 +428,26 @@ class RestApiHandler(BaseHTTPRequestHandler):
def get_postgresql_status(self, retry=False): def get_postgresql_status(self, retry=False):
try: try:
cluster = self.server.patroni.dcs.cluster
if self.server.patroni.postgresql.state not in ('running', 'restarting', 'starting'): if self.server.patroni.postgresql.state not in ('running', 'restarting', 'starting'):
raise RetryFailedError('') raise RetryFailedError('')
stmt = ("WITH replication_info AS (" stmt = ("WITH replication_info AS ("
"SELECT usename, application_name, client_addr, state, sync_state, sync_priority" "SELECT usename, application_name, client_addr, state, sync_state, sync_priority"
" FROM pg_stat_replication) SELECT" " FROM pg_catalog.pg_stat_replication) SELECT"
" to_char(pg_postmaster_start_time(), 'YYYY-MM-DD HH24:MI:SS.MS TZ')," " pg_catalog.to_char(pg_catalog.pg_postmaster_start_time(), 'YYYY-MM-DD HH24:MI:SS.MS TZ'),"
" CASE WHEN pg_is_in_recovery() THEN 0" " CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0"
" ELSE ('x' || SUBSTR(pg_{0}file_name(pg_current_{0}_{1}()), 1, 8))::bit(32)::int END," " ELSE ('x' || pg_catalog.substr(pg_catalog.pg_{0}file_name("
" CASE WHEN pg_is_in_recovery() THEN 0" "pg_catalog.pg_current_{0}_{1}()), 1, 8))::bit(32)::int END,"
" ELSE pg_{0}_{1}_diff(pg_current_{0}_{1}(), '0/0')::bigint END," " CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0"
" pg_{0}_{1}_diff(COALESCE(pg_last_{0}_receive_{1}(), pg_last_{0}_replay_{1}()), '0/0')::bigint," " ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), '0/0')::bigint END,"
" pg_{0}_{1}_diff(pg_last_{0}_replay_{1}(), '0/0')::bigint," " pg_catalog.pg_{0}_{1}_diff(COALESCE(pg_catalog.pg_last_{0}_receive_{1}(),"
" to_char(pg_last_xact_replay_timestamp(), 'YYYY-MM-DD HH24:MI:SS.MS TZ')," " pg_catalog.pg_last_{0}_replay_{1}()), '0/0')::bigint,"
" pg_is_in_recovery() AND pg_is_{0}_replay_paused()," " pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_last_{0}_replay_{1}(), '0/0')::bigint,"
" (SELECT array_to_json(array_agg(row_to_json(ri))) FROM replication_info ri)") " pg_catalog.to_char(pg_catalog.pg_last_xact_replay_timestamp(), 'YYYY-MM-DD HH24:MI:SS.MS TZ'),"
" pg_catalog.pg_is_in_recovery() AND pg_catalog.pg_is_{0}_replay_paused(), "
"(SELECT pg_catalog.array_to_json(pg_catalog.array_agg("
"pg_catalog.row_to_json(ri))) FROM replication_info ri)")
row = self.query(stmt.format(self.server.patroni.postgresql.wal_name, row = self.query(stmt.format(self.server.patroni.postgresql.wal_name,
self.server.patroni.postgresql.lsn_name), retry=retry)[0] self.server.patroni.postgresql.lsn_name), retry=retry)[0]
@@ -436,6 +457,7 @@ class RestApiHandler(BaseHTTPRequestHandler):
'postmaster_start_time': row[0], 'postmaster_start_time': row[0],
'role': 'replica' if row[1] == 0 else 'master', 'role': 'replica' if row[1] == 0 else 'master',
'server_version': self.server.patroni.postgresql.server_version, 'server_version': self.server.patroni.postgresql.server_version,
'cluster_unlocked': bool(not cluster or cluster.is_unlocked()),
'xlog': ({ 'xlog': ({
'received_location': row[3], 'received_location': row[3],
'replayed_location': row[4], 'replayed_location': row[4],
@@ -445,10 +467,12 @@ class RestApiHandler(BaseHTTPRequestHandler):
}) })
} }
if result['role'] == 'replica' and self.server.patroni.ha.is_standby_cluster():
result['role'] = self.server.patroni.postgresql.role
if row[1] > 0: if row[1] > 0:
result['timeline'] = row[1] result['timeline'] = row[1]
else: else:
cluster = self.server.patroni.dcs.cluster
leader_timeline = None if not cluster or cluster.is_unlocked() else cluster.leader.timeline leader_timeline = None if not cluster or cluster.is_unlocked() else cluster.leader.timeline
result['timeline'] = self.server.patroni.postgresql.replica_cached_timeline(leader_timeline) result['timeline'] = self.server.patroni.postgresql.replica_cached_timeline(leader_timeline)
@@ -471,6 +495,7 @@ class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
def __init__(self, patroni, config): def __init__(self, patroni, config):
self.patroni = patroni self.patroni = patroni
self.__listen = None
self.__initialize(config) self.__initialize(config)
self.__set_config_parameters(config) self.__set_config_parameters(config)
self.daemon = True self.daemon = True
@@ -488,8 +513,10 @@ class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
@staticmethod @staticmethod
def _set_fd_cloexec(fd): def _set_fd_cloexec(fd):
flags = fcntl.fcntl(fd, fcntl.F_GETFD) if os.name != 'nt':
fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) import fcntl
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
def check_basic_auth_key(self, key): def check_basic_auth_key(self, key):
return self.__auth_key == key return self.__auth_key == key
@@ -505,18 +532,51 @@ class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
def __get_ssl_options(config): def __get_ssl_options(config):
return {option: config[option] for option in ['certfile', 'keyfile'] if option in config} return {option: config[option] for option in ['certfile', 'keyfile'] if option in config}
def __set_connection_string(self, connect_address):
self.connection_string = '{0}://{1}/patroni'.format(self.__protocol, connect_address or self.__listen)
def __set_config_parameters(self, config): def __set_config_parameters(self, config):
self.__auth_key = base64.b64encode(config['auth'].encode('utf-8')).decode('utf-8') if 'auth' in config else None self.__auth_key = base64.b64encode(config['auth'].encode('utf-8')).decode('utf-8') if 'auth' in config else None
self.__set_connection_string(config.get('connect_address')) self.connection_string = uri(self.__protocol, config.get('connect_address') or self.__listen, 'patroni')
@staticmethod
def __has_dual_stack():
if hasattr(socket, 'AF_INET6') and hasattr(socket, 'IPPROTO_IPV6') and hasattr(socket, 'IPV6_V6ONLY'):
sock = None
try:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
return True
except socket.error as e:
logger.debug('Error when working with ipv6 socket: %s', e)
finally:
if sock:
sock.close()
return False
def __httpserver_init(self, host, port):
dual_stack = self.__has_dual_stack()
if host == '':
host = None
info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
# in case dual stack is not supported we want IPv4 to be preferred over IPv6
info.sort(key=lambda x: x[0] == socket.AF_INET, reverse=not dual_stack)
self.address_family = info[0][0]
HTTPServer.__init__(self, info[0][-1][:2], RestApiHandler)
def __initialize(self, config): def __initialize(self, config):
self.__ssl_options = self.__get_ssl_options(config) try:
host, port = split_host_port(config['listen'], None)
except Exception:
raise ValueError('Invalid "restapi" config: expected <HOST>:<PORT> for "listen", but got "{0}"'
.format(config['listen']))
if self.__listen is not None: # changing config in runtime
self.shutdown()
self.__listen = config['listen'] self.__listen = config['listen']
host, port = config['listen'].rsplit(':', 1) self.__ssl_options = self.__get_ssl_options(config)
HTTPServer.__init__(self, (host, int(port)), RestApiHandler)
self.__httpserver_init(host, port)
Thread.__init__(self, target=self.serve_forever) Thread.__init__(self, target=self.serve_forever)
self._set_fd_cloexec(self.socket) self._set_fd_cloexec(self.socket)
@@ -526,13 +586,23 @@ class RestApiServer(ThreadingMixIn, HTTPServer, Thread):
# Sometime it's also needed to pass reference to a 'keyfile'. # Sometime it's also needed to pass reference to a 'keyfile'.
if self.__ssl_options.get('certfile'): if self.__ssl_options.get('certfile'):
import ssl import ssl
self.socket = ssl.wrap_socket(self.socket, server_side=True, **self.__ssl_options) ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ctx.load_cert_chain(**self.__ssl_options)
self.socket = ctx.wrap_socket(self.socket, server_side=True)
self.__protocol = 'https' self.__protocol = 'https'
self.__set_connection_string(config.get('connect_address')) return True
def reload_config(self, config): def reload_config(self, config):
self.__set_config_parameters(config) if 'listen' not in config: # changing config in runtime
if self.__listen != config['listen'] or self.__ssl_options != self.__get_ssl_options(config): raise ValueError('Can not find "restapi.listen" config')
self.shutdown()
self.__initialize(config) elif (self.__listen != config['listen'] or self.__ssl_options != self.__get_ssl_options(config)) \
and self.__initialize(config):
self.start() self.start()
self.__set_config_parameters(config)
@staticmethod
def handle_error(request, client_address):
address, port = client_address
logger.warning('Exception happened during processing of request from {}:{}'.format(address, port))
logger.warning(traceback.format_exc())
+4 -4
View File
@@ -52,8 +52,8 @@ class CriticalTask(object):
class AsyncExecutor(object): class AsyncExecutor(object):
def __init__(self, state_handler, ha_wakeup): def __init__(self, cancellable, ha_wakeup):
self.state_handler = state_handler self._cancellable = cancellable
self._ha_wakeup = ha_wakeup self._ha_wakeup = ha_wakeup
self._thread_lock = RLock() self._thread_lock = RLock()
self._scheduled_action = None self._scheduled_action = None
@@ -92,7 +92,7 @@ class AsyncExecutor(object):
return return
self._finish_event.clear() self._finish_event.clear()
self.state_handler.reset_is_cancelled() self._cancellable.reset_is_cancelled()
# if the func returned something (not None) - wake up main HA loop # if the func returned something (not None) - wake up main HA loop
wakeup = func(*args) if args else func() wakeup = func(*args) if args else func()
return wakeup return wakeup
@@ -118,7 +118,7 @@ class AsyncExecutor(object):
logger.warning('Cancelling long running task %s', self._scheduled_action) logger.warning('Cancelling long running task %s', self._scheduled_action)
self._is_cancelled = True self._is_cancelled = True
self.state_handler.cancel() self._cancellable.cancel()
self._finish_event.wait() self._finish_event.wait()
with self: with self:
+103 -45
View File
@@ -1,6 +1,7 @@
import json import json
import logging import logging
import os import os
import shutil
import sys import sys
import tempfile import tempfile
import yaml import yaml
@@ -8,8 +9,9 @@ import yaml
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
from patroni.dcs import ClusterConfig from patroni.dcs import ClusterConfig
from patroni.postgresql import Postgresql from patroni.postgresql.config import ConfigHandler
from patroni.utils import deep_compare, parse_int, patch_config from patroni.utils import deep_compare, parse_bool, parse_int, patch_config
from requests.structures import CaseInsensitiveDict
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -41,13 +43,23 @@ class Config(object):
__DEFAULT_CONFIG = { __DEFAULT_CONFIG = {
'ttl': 30, 'loop_wait': 10, 'retry_timeout': 10, 'ttl': 30, 'loop_wait': 10, 'retry_timeout': 10,
'maximum_lag_on_failover': 1048576, 'maximum_lag_on_failover': 1048576,
'check_timeline': False,
'master_start_timeout': 300, 'master_start_timeout': 300,
'synchronous_mode': False, 'synchronous_mode': False,
'synchronous_mode_strict': False, 'synchronous_mode_strict': False,
'standby_cluster': {
'create_replica_methods': '',
'host': '',
'port': '',
'primary_slot_name': '',
'restore_command': '',
'archive_cleanup_command': '',
'recovery_min_apply_delay': ''
},
'postgresql': { 'postgresql': {
'bin_dir': '', 'bin_dir': '',
'use_slots': True, 'use_slots': True,
'parameters': {p: v[0] for p, v in Postgresql.CMDLINE_OPTIONS.items()} 'parameters': CaseInsensitiveDict({p: v[0] for p, v in ConfigHandler.CMDLINE_OPTIONS.items()})
}, },
'watchdog': { 'watchdog': {
'mode': 'automatic', 'mode': 'automatic',
@@ -87,6 +99,9 @@ class Config(object):
def dynamic_configuration(self): def dynamic_configuration(self):
return deepcopy(self._dynamic_configuration) return deepcopy(self._dynamic_configuration)
def check_mode(self, mode):
return bool(parse_bool(self._dynamic_configuration.get(mode)))
def _load_config_file(self): def _load_config_file(self):
"""Loads config.yaml from filesystem and applies some values which were set via ENV""" """Loads config.yaml from filesystem and applies some values which were set via ENV"""
with open(self._config_file) as f: with open(self._config_file) as f:
@@ -110,7 +125,7 @@ class Config(object):
with os.fdopen(fd, 'w') as f: with os.fdopen(fd, 'w') as f:
fd = None fd = None
json.dump(self.dynamic_configuration, f) json.dump(self.dynamic_configuration, f)
tmpfile = os.rename(tmpfile, self._cache_file) tmpfile = shutil.move(tmpfile, self._cache_file)
self._cache_needs_saving = False self._cache_needs_saving = False
except Exception: except Exception:
logger.exception('Exception when saving file: %s', self._cache_file) logger.exception('Exception when saving file: %s', self._cache_file)
@@ -154,6 +169,8 @@ class Config(object):
self._local_configuration = configuration self._local_configuration = configuration
self.__effective_configuration = new_configuration self.__effective_configuration = new_configuration
return True return True
else:
logger.info('No configuration items changed, nothing to reload.')
except Exception: except Exception:
logger.exception('Exception when reloading local configuration from %s', self.config_file) logger.exception('Exception when reloading local configuration from %s', self.config_file)
if dry_run: if dry_run:
@@ -161,11 +178,9 @@ class Config(object):
@staticmethod @staticmethod
def _process_postgresql_parameters(parameters, is_local=False): def _process_postgresql_parameters(parameters, is_local=False):
ret = {} return {name: value for name, value in (parameters or {}).items()
for name, value in (parameters or {}).items(): if name not in ConfigHandler.CMDLINE_OPTIONS or
if name not in Postgresql.CMDLINE_OPTIONS or not is_local and Postgresql.CMDLINE_OPTIONS[name][1](value): not is_local and ConfigHandler.CMDLINE_OPTIONS[name][1](value)}
ret[name] = value
return ret
def _safe_copy_dynamic_configuration(self, dynamic_configuration): def _safe_copy_dynamic_configuration(self, dynamic_configuration):
config = deepcopy(self.__DEFAULT_CONFIG) config = deepcopy(self.__DEFAULT_CONFIG)
@@ -177,6 +192,10 @@ class Config(object):
config['postgresql'][name].update(self._process_postgresql_parameters(value)) config['postgresql'][name].update(self._process_postgresql_parameters(value))
elif name not in ('connect_address', 'listen', 'data_dir', 'pgpass', 'authentication'): elif name not in ('connect_address', 'listen', 'data_dir', 'pgpass', 'authentication'):
config['postgresql'][name] = deepcopy(value) config['postgresql'][name] = deepcopy(value)
elif name == 'standby_cluster':
for name, value in (value or {}).items():
if name in self.__DEFAULT_CONFIG['standby_cluster']:
config['standby_cluster'][name] = deepcopy(value)
elif name in config: # only variables present in __DEFAULT_CONFIG allowed to be overriden from DCS elif name in config: # only variables present in __DEFAULT_CONFIG allowed to be overriden from DCS
if name in ('synchronous_mode', 'synchronous_mode_strict'): if name in ('synchronous_mode', 'synchronous_mode_strict'):
config[name] = value config[name] = value
@@ -196,6 +215,15 @@ class Config(object):
if value: if value:
ret[param] = value ret[param] = value
def _fix_log_env(name, oldname):
value = _popenv(oldname)
name = Config.PATRONI_ENV_PREFIX + 'LOG_' + name.upper()
if value and name not in os.environ:
os.environ[name] = value
for name, oldname in (('level', 'loglevel'), ('format', 'logformat'), ('dateformat', 'log_datefmt')):
_fix_log_env(name, oldname)
def _set_section_values(section, params): def _set_section_values(section, params):
for param in params: for param in params:
value = _popenv(section + '_' + param) value = _popenv(section + '_' + param)
@@ -203,7 +231,24 @@ class Config(object):
ret[section][param] = value ret[section][param] = value
_set_section_values('restapi', ['listen', 'connect_address', 'certfile', 'keyfile']) _set_section_values('restapi', ['listen', 'connect_address', 'certfile', 'keyfile'])
_set_section_values('postgresql', ['listen', 'connect_address', 'data_dir', 'pgpass', 'bin_dir']) _set_section_values('postgresql', ['listen', 'connect_address', 'config_dir', 'data_dir', 'pgpass', 'bin_dir'])
_set_section_values('log', ['level', 'format', 'dateformat', 'max_queue_size',
'dir', 'file_size', 'file_num', 'loggers'])
def _parse_dict(value):
if not value.strip().startswith('{'):
value = '{{{0}}}'.format(value)
try:
return yaml.safe_load(value)
except Exception:
logger.exception('Exception when parsing dict %s', value)
return None
value = ret.get('log', {}).pop('loggers', None)
if value:
value = _parse_dict(value)
if value:
ret['log']['loggers'] = value
def _get_auth(name): def _get_auth(name):
ret = {} ret = {}
@@ -218,7 +263,7 @@ class Config(object):
ret['restapi']['authentication'] = restapi_auth ret['restapi']['authentication'] = restapi_auth
authentication = {} authentication = {}
for user_type in ('replication', 'superuser'): for user_type in ('replication', 'superuser', 'rewind'):
entry = _get_auth(user_type) entry = _get_auth(user_type)
if entry: if entry:
authentication[user_type] = entry authentication[user_type] = entry
@@ -226,8 +271,6 @@ class Config(object):
if authentication: if authentication:
ret['postgresql']['authentication'] = authentication ret['postgresql']['authentication'] = authentication
users = {}
def _parse_list(value): def _parse_list(value):
if not (value.strip().startswith('-') or '[' in value): if not (value.strip().startswith('-') or '[' in value):
value = '[{0}]'.format(value) value = '[{0}]'.format(value)
@@ -239,37 +282,40 @@ class Config(object):
for param in list(os.environ.keys()): for param in list(os.environ.keys()):
if param.startswith(Config.PATRONI_ENV_PREFIX): if param.startswith(Config.PATRONI_ENV_PREFIX):
# PATRONI_(ETCD|CONSUL|ZOOKEEPER|EXHIBITOR|...)_(HOSTS?|PORT|..)
name, suffix = (param[8:].split('_', 1) + [''])[:2] name, suffix = (param[8:].split('_', 1) + [''])[:2]
if name and suffix: if suffix in ('HOST', 'HOSTS', 'PORT', 'USE_PROXIES', 'PROTOCOL', 'SRV', 'URL', 'PROXY',
# PATRONI_(ETCD|CONSUL|ZOOKEEPER|EXHIBITOR|...)_(HOSTS?|PORT|..) 'CACERT', 'CERT', 'KEY', 'VERIFY', 'TOKEN', 'CHECKS', 'DC', 'CONSISTENCY',
if suffix in ('HOST', 'HOSTS', 'PORT', 'SRV', 'URL', 'PROXY', 'CACERT', 'CERT', 'REGISTER_SERVICE', 'SERVICE_CHECK_INTERVAL', 'NAMESPACE', 'CONTEXT',
'KEY', 'VERIFY', 'TOKEN', 'CHECKS', 'DC', 'NAMESPACE', 'CONTEXT', 'USE_ENDPOINTS', 'SCOPE_LABEL', 'ROLE_LABEL', 'POD_IP', 'PORTS', 'LABELS') and name:
'USE_ENDPOINTS', 'SCOPE_LABEL', 'ROLE_LABEL', 'POD_IP', 'PORTS', 'LABELS'): value = os.environ.pop(param)
value = os.environ.pop(param) if suffix == 'PORT':
if suffix == 'PORT': value = value and parse_int(value)
value = value and parse_int(value) elif suffix in ('HOSTS', 'PORTS', 'CHECKS'):
elif suffix in ('HOSTS', 'PORTS', 'CHECKS'): value = value and _parse_list(value)
value = value and _parse_list(value) elif suffix == 'LABELS':
elif suffix == 'LABELS': value = _parse_dict(value)
if not value.strip().startswith('{'): elif suffix in ('USE_PROXIES', 'REGISTER_SERVICE'):
value = '{{{0}}}'.format(value) value = parse_bool(value)
try: if value:
value = yaml.safe_load(value) ret[name.lower()][suffix.lower()] = value
except Exception: if 'etcd' in ret:
logger.exception('Exception when parsing dict %s', value) ret['etcd'].update(_get_auth('etcd'))
value = None
if value: users = {}
ret[name.lower()][suffix.lower()] = value for param in list(os.environ.keys()):
# PATRONI_<username>_PASSWORD=<password>, PATRONI_<username>_OPTIONS=<option1,option2,...> if param.startswith(Config.PATRONI_ENV_PREFIX):
# CREATE USER "<username>" WITH <OPTIONS> PASSWORD '<password>' name, suffix = (param[8:].rsplit('_', 1) + [''])[:2]
elif suffix == 'PASSWORD': # PATRONI_<username>_PASSWORD=<password>, PATRONI_<username>_OPTIONS=<option1,option2,...>
password = os.environ.pop(param) # CREATE USER "<username>" WITH <OPTIONS> PASSWORD '<password>'
if password: if name and suffix == 'PASSWORD':
users[name] = {'password': password} password = os.environ.pop(param)
options = os.environ.pop(param[:-9] + '_OPTIONS', None) if password:
options = options and _parse_list(options) users[name] = {'password': password}
if options: options = os.environ.pop(param[:-9] + '_OPTIONS', None)
users[name]['options'] = options options = options and _parse_list(options)
if options:
users[name]['options'] = options
if users: if users:
ret['bootstrap']['users'] = users ret['bootstrap']['users'] = users
@@ -286,6 +332,11 @@ class Config(object):
config['postgresql'][name] = deepcopy(value) config['postgresql'][name] = deepcopy(value)
elif name not in config or name in ['watchdog']: elif name not in config or name in ['watchdog']:
config[name] = deepcopy(value) if value else {} config[name] = deepcopy(value) if value else {}
if os.getenv("PATRONI_DEBUG_MODE"):
config['ttl'] = 24 * 60 * 60 # practical infinity for a debugging session
config['loop_wait'] = -1
# restapi server expects to get restapi.auth = 'username:password' # restapi server expects to get restapi.auth = 'username:password'
if 'authentication' in config['restapi']: if 'authentication' in config['restapi']:
@@ -311,8 +362,15 @@ class Config(object):
if 'name' not in config and 'name' in pg_config: if 'name' not in config and 'name' in pg_config:
config['name'] = pg_config['name'] config['name'] = pg_config['name']
pg_config.update({p: config[p] for p in ('name', 'scope', 'retry_timeout', updated_fields = (
'synchronous_mode', 'maximum_lag_on_failover') if p in config}) 'name',
'scope',
'retry_timeout',
'synchronous_mode',
'synchronous_mode_strict',
)
pg_config.update({p: config[p] for p in updated_fields if p in config})
return config return config
+141 -33
View File
@@ -14,7 +14,6 @@ import io
import json import json
import logging import logging
import os import os
import psycopg2
import random import random
import requests import requests
import subprocess import subprocess
@@ -30,6 +29,7 @@ from patroni.config import Config
from patroni.dcs import get_dcs as _get_dcs from patroni.dcs import get_dcs as _get_dcs
from patroni.exceptions import PatroniException from patroni.exceptions import PatroniException
from patroni.postgresql import Postgresql from patroni.postgresql import Postgresql
from patroni.postgresql.misc import postgres_version_to_int
from patroni.utils import patch_config, polling_loop from patroni.utils import patch_config, polling_loop
from patroni.version import __version__ from patroni.version import __version__
from prettytable import PrettyTable from prettytable import PrettyTable
@@ -63,12 +63,15 @@ def parse_dcs(dcs):
elif scheme not in DCS_DEFAULTS: elif scheme not in DCS_DEFAULTS:
raise PatroniCtlException('Unknown dcs scheme: {}'.format(scheme)) raise PatroniCtlException('Unknown dcs scheme: {}'.format(scheme))
dcs_info = DCS_DEFAULTS[scheme] default = DCS_DEFAULTS[scheme]
return yaml.load(dcs_info['template'].format(host=parsed.hostname or 'localhost', port=port or dcs_info['port'])) return yaml.safe_load(default['template'].format(host=parsed.hostname or 'localhost', port=port or default['port']))
def load_config(path, dcs): def load_config(path, dcs):
logging.debug('Loading configuration from file %s', path) 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)
else:
logging.debug('Loading configuration from file %s', path)
config = {} config = {}
old_argv = list(sys.argv) old_argv = list(sys.argv)
try: try:
@@ -103,15 +106,24 @@ option_watch = click.option('-W', is_flag=True, help='Auto update the screen eve
option_force = click.option('--force', is_flag=True, help='Do not ask for confirmation at any point') option_force = click.option('--force', is_flag=True, help='Do not ask for confirmation at any point')
arg_cluster_name = click.argument('cluster_name', required=False, arg_cluster_name = click.argument('cluster_name', required=False,
default=lambda: click.get_current_context().obj.get('scope')) default=lambda: click.get_current_context().obj.get('scope'))
option_insecure = click.option('-k', '--insecure', is_flag=True, help='Allow connections to SSL sites without certs')
@click.group() @click.group()
@click.option('--config-file', '-c', help='Configuration file', default=CONFIG_FILE_PATH) @click.option('--config-file', '-c', help='Configuration file',
envvar='PATRONICTL_CONFIG_FILE', default=CONFIG_FILE_PATH)
@click.option('--dcs', '-d', help='Use this DCS', envvar='DCS') @click.option('--dcs', '-d', help='Use this DCS', envvar='DCS')
@option_insecure
@click.pass_context @click.pass_context
def ctl(ctx, config_file, dcs): def ctl(ctx, config_file, dcs, insecure):
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=os.environ.get('LOGLEVEL', 'WARNING')) level = 'WARNING'
for name in ('LOGLEVEL', 'PATRONI_LOGLEVEL', 'PATRONI_LOG_LEVEL'):
level = os.environ.get(name, level)
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=level)
logging.captureWarnings(True) # Capture eventual SSL warning
ctx.obj = load_config(config_file, dcs) ctx.obj = load_config(config_file, dcs)
# backward compatibility for configuration file where ctl section is not define
ctx.obj.setdefault('ctl', {})['insecure'] = ctx.obj.get('ctl', {}).get('insecure') or insecure
def get_dcs(config, scope): def get_dcs(config, scope):
@@ -129,6 +141,7 @@ def auth_header(config):
def request_patroni(member, request_type, endpoint, content=None, headers=None): def request_patroni(member, request_type, endpoint, content=None, headers=None):
ctx = click.get_current_context() # the current click context
headers = headers or {} headers = headers or {}
url_parts = urlparse(member.api_url) url_parts = urlparse(member.api_url)
logging.debug(url_parts) logging.debug(url_parts)
@@ -137,8 +150,21 @@ def request_patroni(member, request_type, endpoint, content=None, headers=None):
url = '{0}://{1}/{2}'.format(url_parts.scheme, url_parts.netloc, endpoint) url = '{0}://{1}/{2}'.format(url_parts.scheme, url_parts.netloc, endpoint)
insecure = ctx.obj.get('ctl', {}).get('insecure', False)
# Get certfile if any from several configuration namespace
cert = ctx.obj.get('ctl', {}).get('cacert') or \
ctx.obj.get('restapi', {}).get('cacert') or \
ctx.obj.get('restapi', {}).get('certfile')
# In the case we specificaly disable SSL cert verification we don't want to have the warning
if insecure:
verify = False
elif cert:
verify = cert
else:
verify = True
return getattr(requests, request_type)(url, headers=headers, return getattr(requests, request_type)(url, headers=headers,
data=json.dumps(content) if content else None, timeout=60) data=json.dumps(content) if content else None, timeout=60,
verify=verify)
def print_output(columns, rows=None, alignment=None, fmt='pretty', header=True, delimiter='\t'): def print_output(columns, rows=None, alignment=None, fmt='pretty', header=True, delimiter='\t'):
@@ -161,7 +187,7 @@ def print_output(columns, rows=None, alignment=None, fmt='pretty', header=True,
if fmt == 'tsv': if fmt == 'tsv':
if columns is not None and header: if columns is not None and header:
click.echo(delimiter.join(columns) + '\n') click.echo(delimiter.join(columns))
for r in rows: for r in rows:
c = [str(c) for c in r] c = [str(c) for c in r]
@@ -227,13 +253,14 @@ def get_cursor(cluster, connect_parameters, role='master', member=None):
else: else:
params.pop('database') params.pop('database')
import psycopg2
conn = psycopg2.connect(**params) conn = psycopg2.connect(**params)
conn.autocommit = True conn.autocommit = True
cursor = conn.cursor() cursor = conn.cursor()
if role == 'any': if role == 'any':
return cursor return cursor
cursor.execute('SELECT pg_is_in_recovery()') cursor.execute('SELECT pg_catalog.pg_is_in_recovery()')
in_recovery = cursor.fetchone()[0] in_recovery = cursor.fetchone()[0]
if in_recovery and role == 'replica' or not in_recovery and role == 'master': if in_recovery and role == 'replica' or not in_recovery and role == 'master':
@@ -244,7 +271,7 @@ def get_cursor(cluster, connect_parameters, role='master', member=None):
return None return None
def get_members(cluster, cluster_name, member_names, role, force, action): def get_members(cluster, cluster_name, member_names, role, force, action, scheduled_at=None):
candidates = {m.name: m for m in cluster.members} candidates = {m.name: m for m in cluster.members}
if not force or role: if not force or role:
@@ -267,10 +294,18 @@ def get_members(cluster, cluster_name, member_names, role, force, action):
if member_name not in candidates: if member_name not in candidates:
raise PatroniCtlException('{0} is not a member of cluster'.format(member_name)) raise PatroniCtlException('{0} is not a member of cluster'.format(member_name))
if not force: if scheduled_at:
confirm = click.confirm('Are you sure you want to {0} members {1}?'.format(action, ', '.join(member_names))) if not force:
if not confirm: confirm = click.confirm('Are you sure you want to schedule {0} of members {1} at {2}?'
raise PatroniCtlException('Aborted {0}'.format(action)) .format(action, ', '.join(member_names), scheduled_at))
if not confirm:
raise PatroniCtlException('Aborted scheduled {0}'.format(action))
else:
if not force:
confirm = click.confirm('Are you sure you want to {0} members {1}?'
.format(action, ', '.join(member_names)))
if not confirm:
raise PatroniCtlException('Aborted {0}'.format(action))
return [candidates[n] for n in member_names] return [candidates[n] for n in member_names]
@@ -361,6 +396,7 @@ def query(
def query_member(cluster, cursor, member, role, command, connect_parameters): def query_member(cluster, cursor, member, role, command, connect_parameters):
import psycopg2
try: try:
if cursor is None: if cursor is None:
cursor = get_cursor(cluster, connect_parameters, role=role, member=member) cursor = get_cursor(cluster, connect_parameters, role=role, member=member)
@@ -373,7 +409,7 @@ 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_is_in_recovery()') cursor.execute('SELECT pg_catalog.pg_is_in_recovery()')
in_recovery = cursor.fetchone()[0] in_recovery = cursor.fetchone()[0]
if in_recovery and role == 'master' or not in_recovery and role == 'replica': if in_recovery and role == 'master' or not in_recovery and role == 'replica':
@@ -445,6 +481,33 @@ def parse_scheduled(scheduled):
return None return None
@ctl.command('reload', help='Reload cluster member configuration')
@click.argument('cluster_name')
@click.argument('member_names', nargs=-1)
@click.option('--role', '-r', help='Reload only members with this role', default='any',
type=click.Choice(['master', 'replica', 'any']))
@option_force
@click.pass_obj
def reload(obj, cluster_name, member_names, force, role):
cluster = get_dcs(obj, cluster_name).get_cluster()
members = get_members(cluster, cluster_name, member_names, role, force, 'reload')
content = {}
for member in members:
r = request_patroni(member, 'post', 'reload', content, auth_header(obj))
if r.status_code == 200:
click.echo('No changes to apply on member {0}'.format(member.name))
elif r.status_code == 202:
click.echo('Reload request received for member {0} and will be processed within {1} seconds'.format(
member.name, cluster.config.data.get('loop_wait'))
)
else:
click.echo('Failed: reload for member {0}, status code={1}, ({2})'.format(
member.name, r.status_code, r.text)
)
@ctl.command('restart', help='Restart cluster member') @ctl.command('restart', help='Restart cluster member')
@click.argument('cluster_name') @click.argument('cluster_name')
@click.argument('member_names', nargs=-1) @click.argument('member_names', nargs=-1)
@@ -463,7 +526,14 @@ def parse_scheduled(scheduled):
def restart(obj, cluster_name, member_names, force, role, p_any, scheduled, version, pending, timeout): def restart(obj, cluster_name, member_names, force, role, p_any, scheduled, version, pending, timeout):
cluster = get_dcs(obj, cluster_name).get_cluster() cluster = get_dcs(obj, cluster_name).get_cluster()
members = get_members(cluster, cluster_name, member_names, role, force, 'restart') if scheduled is None and not force:
next_hour = (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M')
scheduled = click.prompt('When should the restart take place (e.g. ' + next_hour + ') ',
type=str, default='now')
scheduled_at = parse_scheduled(scheduled)
members = get_members(cluster, cluster_name, member_names, role, force, 'restart', scheduled_at)
if p_any: if p_any:
random.shuffle(members) random.shuffle(members)
members = members[:1] members = members[:1]
@@ -478,16 +548,12 @@ def restart(obj, cluster_name, member_names, force, role, p_any, scheduled, vers
if version: if version:
try: try:
Postgresql.postgres_version_to_int(version) postgres_version_to_int(version)
except PatroniException as e: except PatroniException as e:
raise PatroniCtlException(e.value) raise PatroniCtlException(e.value)
content['postgres_version'] = version content['postgres_version'] = version
if scheduled is None and not force:
scheduled = click.prompt('When should the restart take place (e.g. 2015-10-01T14:30) ', type=str, default='now')
scheduled_at = parse_scheduled(scheduled)
if scheduled_at: if scheduled_at:
if cluster.is_paused(): if cluster.is_paused():
raise PatroniCtlException("Can't schedule restart in the paused state") raise PatroniCtlException("Can't schedule restart in the paused state")
@@ -558,7 +624,8 @@ def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, for
if master is not None and cluster.leader and cluster.leader.member.name != master: if master is not None and cluster.leader and cluster.leader.member.name != master:
raise PatroniCtlException('Member {0} is not the leader of cluster {1}'.format(master, cluster_name)) raise PatroniCtlException('Member {0} is not the leader of cluster {1}'.format(master, cluster_name))
candidate_names = [str(m.name) for m in cluster.members if m.name != master] # excluding members with nofailover tag
candidate_names = [str(m.name) for m in cluster.members if m.name != master and not m.nofailover]
# We sort the names for consistent output to the client # We sort the names for consistent output to the client
candidate_names.sort() candidate_names.sort()
@@ -578,10 +645,12 @@ def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, for
raise PatroniCtlException('Member {0} does not exist in cluster {1}'.format(candidate, cluster_name)) raise PatroniCtlException('Member {0} does not exist in cluster {1}'.format(candidate, cluster_name))
scheduled_at_str = None scheduled_at_str = None
scheduled_at = None
if action == 'switchover': if action == 'switchover':
if scheduled is None and not force: if scheduled is None and not force:
scheduled = click.prompt('When should the switchover take place (e.g. 2015-10-01T14:30) ', next_hour = (datetime.datetime.now() + datetime.timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M')
scheduled = click.prompt('When should the switchover take place (e.g. ' + next_hour + ' ) ',
type=str, default='now') type=str, default='now')
scheduled_at = parse_scheduled(scheduled) scheduled_at = parse_scheduled(scheduled)
@@ -600,9 +669,14 @@ def _do_failover_or_switchover(obj, action, cluster_name, master, candidate, for
if not force: if not force:
demote_msg = ', demoting current master ' + master if master else '' demote_msg = ', demoting current master ' + master if master else ''
if scheduled_at_str:
if not click.confirm('Are you sure you want to {0} cluster {1}{2}?'.format(action, cluster_name, demote_msg)): if not click.confirm('Are you sure you want to schedule {0} of cluster {1} at {2}{3}?'
raise PatroniCtlException('Aborting ' + action) .format(action, cluster_name, scheduled_at_str, demote_msg)):
raise PatroniCtlException('Aborting scheduled ' + action)
else:
if not click.confirm('Are you sure you want to {0} cluster {1}{2}?'
.format(action, cluster_name, demote_msg)):
raise PatroniCtlException('Aborting ' + action)
r = None r = None
try: try:
@@ -669,6 +743,10 @@ def output_members(cluster, name, extended=False, fmt='pretty'):
has_scheduled_restarts = any(m.data.get('scheduled_restart') for m in cluster.members) has_scheduled_restarts = any(m.data.get('scheduled_restart') for m in cluster.members)
has_pending_restarts = any(m.data.get('pending_restart') for m in cluster.members) has_pending_restarts = any(m.data.get('pending_restart') for m in cluster.members)
# 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(str(m.conn_kwargs()['port']) != '5432' for m in cluster.members) or\
len(set(m.conn_kwargs()['host'] for m in cluster.members)) < len(cluster.members)
for m in cluster.members: for m in cluster.members:
logging.debug(m) logging.debug(m)
@@ -685,7 +763,11 @@ def output_members(cluster, name, extended=False, fmt='pretty'):
elif xlog_location_cluster >= xlog_location: elif xlog_location_cluster >= xlog_location:
lag = round((xlog_location_cluster - xlog_location)/1024/1024) lag = round((xlog_location_cluster - xlog_location)/1024/1024)
row = [name, m.name, m.conn_kwargs()['host'], role, m.data.get('state', ''), lag] host = m.conn_kwargs()['host']
if append_port:
host += ':{0}'.format(m.conn_kwargs()['port'])
row = [name, m.name, host, role, m.data.get('state', ''), m.data.get('timeline', ''), lag]
if extended or has_pending_restarts: if extended or has_pending_restarts:
row.append('*' if m.data.get('pending_restart') else '') row.append('*' if m.data.get('pending_restart') else '')
@@ -702,8 +784,8 @@ def output_members(cluster, name, extended=False, fmt='pretty'):
rows.append(row) rows.append(row)
columns = ['Cluster', 'Member', 'Host', 'Role', 'State', 'Lag in MB'] columns = ['Cluster', 'Member', 'Host', 'Role', 'State', 'TL', 'Lag in MB']
alignment = {'Lag in MB': 'r'} alignment = {'Lag in MB': 'r', 'TL': 'r'}
if extended or has_pending_restarts: if extended or has_pending_restarts:
columns.append('Pending restart') columns.append('Pending restart')
@@ -786,7 +868,7 @@ def touch_member(config, dcs):
'role': p.role 'role': p.role
} }
return dcs.touch_member(json.dumps(data, separators=(',', ':')), permanent=True) return dcs.touch_member(data, permanent=True)
def set_defaults(config, cluster_name): def set_defaults(config, cluster_name):
@@ -875,7 +957,8 @@ def toggle_pause(config, cluster_name, paused, wait):
for member in members: for member in members:
try: try:
r = request_patroni(member, 'patch', 'config', {'pause': paused or None}, auth_header(config)) r = request_patroni(member, 'patch', 'config', {'pause': paused or None}, auth_header(config))
except Exception: except Exception as err:
logging.warning(str(err))
logging.warning('Member %s is not accessible', member.name) logging.warning('Member %s is not accessible', member.name)
continue continue
@@ -1023,15 +1106,40 @@ def apply_yaml_file(data, filename):
return format_config_for_editing(changed_data), changed_data return format_config_for_editing(changed_data), changed_data
def find_executable(executable, path=None):
_, ext = os.path.splitext(executable)
if (sys.platform == 'win32') and (ext != '.exe'):
executable = executable + '.exe'
if os.path.isfile(executable):
return executable
if path is None:
path = os.environ.get('PATH', os.defpath)
for p in path.split(os.pathsep):
f = os.path.join(p, executable)
if os.path.isfile(f):
return f
def invoke_editor(before_editing, cluster_name): def invoke_editor(before_editing, cluster_name):
"""Starts editor command to edit configuration in human readable format """Starts editor command to edit configuration in human readable format
:param before_editing: human representation before editing :param before_editing: human representation before editing
:returns tuple of human readable and parsed datastructure after changes :returns tuple of human readable and parsed datastructure after changes
""" """
editor_cmd = os.environ.get('EDITOR') editor_cmd = os.environ.get('EDITOR')
if not editor_cmd: if not editor_cmd:
raise PatroniCtlException('EDITOR environment variable is not set') for editor in ('editor', 'vi'):
editor_cmd = find_executable(editor)
if editor_cmd:
logging.debug('Setting fallback editor_cmd=%s', editor)
break
if not editor_cmd:
raise PatroniCtlException('EDITOR environment variable is not set. editor or vi are not available')
with temporary_file(contents=before_editing.encode('utf-8'), with temporary_file(contents=before_editing.encode('utf-8'),
suffix='.yaml', suffix='.yaml',
+189 -22
View File
@@ -6,18 +6,39 @@ import json
import logging import logging
import os import os
import pkgutil import pkgutil
import re
import six import six
import sys import sys
import time
from collections import namedtuple from collections import defaultdict, namedtuple
from copy import deepcopy
from patroni.exceptions import PatroniException from patroni.exceptions import PatroniException
from patroni.utils import parse_bool, uri
from random import randint from random import randint
from six.moves.urllib_parse import urlparse, urlunparse, parse_qsl from six.moves.urllib_parse import urlparse, urlunparse, parse_qsl
from threading import Event, Lock from threading import Event, Lock
slot_name_re = re.compile('^[a-z0-9_]{1,63}$')
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def slot_name_from_member_name(member_name):
"""Translate member name to valid PostgreSQL slot name.
PostgreSQL replication slot names must be valid PostgreSQL names. This function maps the wider space of
member names to valid PostgreSQL names. Names are lowercased, dashes and periods common in hostnames
are replaced with underscores, other characters are encoded as their unicode codepoint. Name is truncated
to 64 characters. Multiple different member names may map to a single slot name."""
def replace_char(match):
c = match.group(0)
return '_' if c in '-.' else "u{:04d}".format(ord(c))
slot_name = re.sub('[^a-z0-9_]', replace_char, member_name.lower())
return slot_name[0:63]
def parse_connection_string(value): def parse_connection_string(value):
"""Original Governor stores connection strings for each cluster members if a following format: """Original Governor stores connection strings for each cluster members if a following format:
postgres://{username}:{password}@{connect_address}/postgres postgres://{username}:{password}@{connect_address}/postgres
@@ -107,12 +128,26 @@ class Member(namedtuple('Member', 'index,name,session,data')):
@property @property
def conn_url(self): def conn_url(self):
return self.data.get('conn_url') conn_url = self.data.get('conn_url')
conn_kwargs = self.data.get('conn_kwargs')
if conn_url:
return conn_url
if conn_kwargs:
conn_url = uri('postgresql', (conn_kwargs.get('host'), conn_kwargs.get('port', 5432)))
self.data['conn_url'] = conn_url
return conn_url
def conn_kwargs(self, auth=None): def conn_kwargs(self, auth=None):
defaults = {
"host": "",
"port": "",
"database": ""
}
ret = self.data.get('conn_kwargs') ret = self.data.get('conn_kwargs')
if ret: if ret:
ret = ret.copy() defaults.update(ret)
ret = defaults
else: else:
r = urlparse(self.conn_url) r = urlparse(self.conn_url)
ret = { ret = {
@@ -158,6 +193,26 @@ class Member(namedtuple('Member', 'index,name,session,data')):
return self.state == 'running' return self.state == 'running'
class RemoteMember(Member):
""" Represents a remote master for a standby cluster
"""
def __new__(cls, name, data):
return super(RemoteMember, cls).__new__(cls, None, name, None, data)
@staticmethod
def allowed_keys():
return ('primary_slot_name',
'create_replica_methods',
'restore_command',
'archive_cleanup_command',
'recovery_min_apply_delay',
'no_replication_slot')
def __getattr__(self, name):
if name in RemoteMember.allowed_keys():
return self.data.get(name)
class Leader(namedtuple('Leader', 'index,session,member')): class Leader(namedtuple('Leader', 'index,session,member')):
"""Immutable object (namedtuple) which represents leader key. """Immutable object (namedtuple) which represents leader key.
@@ -181,6 +236,20 @@ class Leader(namedtuple('Leader', 'index,session,member')):
def timeline(self): def timeline(self):
return self.member.data.get('timeline') return self.member.data.get('timeline')
@property
def checkpoint_after_promote(self):
"""
>>> Leader(1, '', Member.from_node(1, '', '', '{"version":"z"}')).checkpoint_after_promote
"""
version = self.member.data.get('version')
if version:
try:
# 1.5.6 is the last version which doesn't expose checkpoint_after_promote: false
if tuple(map(int, version.split('.'))) > (1, 5, 6):
return self.member.data['role'] == 'master' and 'checkpoint_after_promote' not in self.member.data
except Exception:
logger.debug('Failed to parse Patroni version %s', version)
class Failover(namedtuple('Failover', 'index,leader,candidate,scheduled_at')): class Failover(namedtuple('Failover', 'index,leader,candidate,scheduled_at')):
@@ -235,14 +304,24 @@ class ClusterConfig(namedtuple('ClusterConfig', 'index,data,modify_index')):
def from_node(index, data, modify_index=None): def from_node(index, data, modify_index=None):
""" """
>>> ClusterConfig.from_node(1, '{') is None >>> ClusterConfig.from_node(1, '{') is None
True False
""" """
try: try:
data = json.loads(data) data = json.loads(data)
except (TypeError, ValueError): except (TypeError, ValueError):
return None data = None
return ClusterConfig(index, data, modify_index or index) modify_index = 0
if not isinstance(data, dict):
data = {}
return ClusterConfig(index, data, index if modify_index is None else modify_index)
@property
def permanent_slots(self):
return isinstance(self.data, dict) and (
self.data.get('permanent_replication_slots') or
self.data.get('permanent_slots') or self.data.get('slots')
) or {}
class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')): class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')):
@@ -301,7 +380,7 @@ class SyncState(namedtuple('SyncState', 'index,leader,sync_standby')):
return name is not None and name in (self.leader, self.sync_standby) return name is not None and name in (self.leader, self.sync_standby)
class TimelineHistory(namedtuple('TimelineHistory', 'index,lines')): class TimelineHistory(namedtuple('TimelineHistory', 'index,value,lines')):
"""Object representing timeline history file""" """Object representing timeline history file"""
@staticmethod @staticmethod
@@ -317,7 +396,7 @@ class TimelineHistory(namedtuple('TimelineHistory', 'index,lines')):
lines = None lines = None
if not isinstance(lines, list): if not isinstance(lines, list):
lines = [] lines = []
return TimelineHistory(index, lines) return TimelineHistory(index, value, lines)
class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operation,members,failover,sync,history')): class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operation,members,failover,sync,history')):
@@ -349,14 +428,93 @@ class Cluster(namedtuple('Cluster', 'initialize,config,leader,last_leader_operat
candidates = [m for m in self.members if m.clonefrom and m.is_running and m.name not in exclude] candidates = [m for m in self.members if m.clonefrom and m.is_running and m.name not in exclude]
return candidates[randint(0, len(candidates) - 1)] if candidates else self.leader return candidates[randint(0, len(candidates) - 1)] if candidates else self.leader
def check_mode(self, mode):
return bool(self.config and parse_bool(self.config.data.get(mode)))
def is_paused(self): def is_paused(self):
return self.config and self.config.data.get('pause', False) or False return self.check_mode('pause')
def is_synchronous_mode(self): def is_synchronous_mode(self):
return bool(self.config and self.config.data.get('synchronous_mode')) return self.check_mode('synchronous_mode')
def is_synchronous_mode_strict(self): def get_replication_slots(self, name, role):
return bool(self.config and self.config.data.get('synchronous_mode_strict')) # if the replicatefrom tag is set on the member - we should not create the replication slot for it on
# the current master, because that member would replicate from elsewhere. We still create the slot if
# the replicatefrom destination member is currently not a member of the cluster (fallback to the
# master), or if replicatefrom destination member happens to be the current master
if role in ('master', 'standby_leader'):
slot_members = [m.name for m in self.members if m.name != name and
(m.replicatefrom is None or m.replicatefrom == name or
not self.has_member(m.replicatefrom))]
permanent_slots = (self.config and self.config.permanent_slots or {}).copy()
else:
# only manage slots for replicas that replicate from this one, except for the leader among them
slot_members = [m.name for m in self.members if m.replicatefrom == name and m.name != self.leader.name]
permanent_slots = {}
slots = {slot_name_from_member_name(name): {'type': 'physical'} for name in slot_members}
if len(slots) < len(slot_members):
# Find which names are conflicting for a nicer error message
slot_conflicts = defaultdict(list)
for name in slot_members:
slot_conflicts[slot_name_from_member_name(name)].append(name)
logger.error("Following cluster members share a replication slot name: %s",
"; ".join("{} map to {}".format(", ".join(v), k)
for k, v in slot_conflicts.items() if len(v) > 1))
# "merge" replication slots for members with permanent_replication_slots
for name, value in permanent_slots.items():
if not slot_name_re.match(name):
logger.error("Invalid permanent replication slot name '%s'", name)
logger.error("Slot name may only contain lower case letters, numbers, and the underscore chars")
continue
if name in slots:
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 'type' not in value:
value['type'] = 'logical' if value.get('database') and value.get('plugin') else 'physical'
if value['type'] == 'physical' or value['type'] == 'logical' \
and value.get('database') and value.get('plugin'):
slots[name] = value
continue
logger.error("Bad value for slot '%s' in permanent_slots: %s", name, permanent_slots[name])
return slots
def has_permanent_logical_slots(self, name):
slots = self.get_replication_slots(name, 'master').values()
return any(v for v in slots if v.get("type") == "logical")
@property
def timeline(self):
"""
>>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline
0
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline
1
>>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline
0
"""
if self.history:
if self.history.lines:
try:
return int(self.history.lines[-1][0]) + 1
except Exception:
logger.error('Failed to parse cluster history from DCS: %s', self.history.lines)
elif self.history.value == '[]':
return 1
return 0
@six.add_metaclass(abc.ABCMeta) @six.add_metaclass(abc.ABCMeta)
@@ -378,11 +536,12 @@ class AbstractDCS(object):
i.e.: `zookeeper` for zookeeper, `etcd` for etcd, etc... i.e.: `zookeeper` for zookeeper, `etcd` for etcd, etc...
""" """
self._name = config['name'] self._name = config['name']
self._base_path = os.path.join('/', config.get('namespace', '/service/').strip('/'), config['scope']) self._base_path = re.sub('/+', '/', '/'.join(['', config.get('namespace', 'service'), config['scope']]))
self._set_loop_wait(config.get('loop_wait', 10)) self._set_loop_wait(config.get('loop_wait', 10))
self._ctl = bool(config.get('patronictl', False)) self._ctl = bool(config.get('patronictl', False))
self._cluster = None self._cluster = None
self._cluster_valid_till = 0
self._cluster_thread_lock = Lock() self._cluster_thread_lock = Lock()
self._last_leader_operation = '' self._last_leader_operation = ''
self.event = Event() self.event = Event()
@@ -430,6 +589,10 @@ class AbstractDCS(object):
def set_ttl(self, ttl): def set_ttl(self, ttl):
"""Set the new ttl value for leader key""" """Set the new ttl value for leader key"""
@abc.abstractmethod
def ttl(self):
"""Get new ttl value"""
@abc.abstractmethod @abc.abstractmethod
def set_retry_timeout(self, retry_timeout): def set_retry_timeout(self, retry_timeout):
"""Set the new value for retry_timeout""" """Set the new value for retry_timeout"""
@@ -457,22 +620,26 @@ class AbstractDCS(object):
instance would be demoted.""" instance would be demoted."""
def get_cluster(self): def get_cluster(self):
try:
cluster = self._load_cluster()
except Exception:
self.reset_cluster()
raise
with self._cluster_thread_lock: with self._cluster_thread_lock:
try: self._cluster = cluster
self._load_cluster() self._cluster_valid_till = time.time() + self.ttl
except Exception: return cluster
self._cluster = None
raise
return self._cluster
@property @property
def cluster(self): def cluster(self):
with self._cluster_thread_lock: with self._cluster_thread_lock:
return self._cluster return self._cluster if self._cluster_valid_till > time.time() else None
def reset_cluster(self): def reset_cluster(self):
with self._cluster_thread_lock: with self._cluster_thread_lock:
self._cluster = None self._cluster = None
self._cluster_valid_till = 0
@abc.abstractmethod @abc.abstractmethod
def _write_leader_optime(self, last_operation): def _write_leader_optime(self, last_operation):
@@ -494,7 +661,7 @@ class AbstractDCS(object):
You have to use CAS (Compare And Swap) operation in order to update leader key, You have to use CAS (Compare And Swap) operation in order to update leader key,
for example for etcd `prevValue` parameter must be used.""" for example for etcd `prevValue` parameter must be used."""
def update_leader(self, last_operation): def update_leader(self, last_operation, access_is_restricted=False):
"""Update leader key (or session) ttl and optime/leader """Update leader key (or session) ttl and optime/leader
:param last_operation: absolute xlog location in bytes :param last_operation: absolute xlog location in bytes
@@ -538,7 +705,7 @@ class AbstractDCS(object):
"""Create or update `/config` key""" """Create or update `/config` key"""
@abc.abstractmethod @abc.abstractmethod
def touch_member(self, data, ttl=None, permanent=False): def touch_member(self, data, permanent=False):
"""Update member key in DCS. """Update member key in DCS.
This method should create or update key with the name = '/members/' + `~self._name` This method should create or update key with the name = '/members/' + `~self._name`
and value = data in a given DCS. and value = data in a given DCS.
+147 -25
View File
@@ -2,6 +2,7 @@ from __future__ import absolute_import
import json import json
import logging import logging
import os import os
import re
import socket import socket
import ssl import ssl
import time import time
@@ -10,9 +11,9 @@ import urllib3
from consul import ConsulException, NotFound, base from consul import ConsulException, NotFound, base
from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState, TimelineHistory from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState, TimelineHistory
from patroni.exceptions import DCSError from patroni.exceptions import DCSError
from patroni.utils import deep_compare, parse_bool, Retry, RetryFailedError, split_host_port from patroni.utils import deep_compare, parse_bool, Retry, RetryFailedError, split_host_port, uri
from urllib3.exceptions import HTTPError from urllib3.exceptions import HTTPError
from six.moves.urllib.parse import urlencode, urlparse from six.moves.urllib.parse import urlencode, urlparse, quote
from six.moves.http_client import HTTPException from six.moves.http_client import HTTPException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -26,16 +27,20 @@ class ConsulInternalError(ConsulException):
"""An internal Consul server error occurred""" """An internal Consul server error occurred"""
class InvalidSessionTTL(ConsulInternalError): class InvalidSessionTTL(ConsulException):
"""Session TTL is too small or too big""" """Session TTL is too small or too big"""
class InvalidSession(ConsulException):
"""invalid session"""
class HTTPClient(object): class HTTPClient(object):
def __init__(self, host='127.0.0.1', port=8500, token=None, scheme='http', verify=True, cert=None, ca_cert=None): def __init__(self, host='127.0.0.1', port=8500, token=None, scheme='http', verify=True, cert=None, ca_cert=None):
self.token = token self.token = token
self._read_timeout = 10 self._read_timeout = 10
self.base_uri = '{0}://{1}:{2}'.format(scheme, host, port) self.base_uri = uri(scheme, (host, port))
kwargs = {} kwargs = {}
if cert: if cert:
if isinstance(cert, tuple): if isinstance(cert, tuple):
@@ -71,6 +76,8 @@ class HTTPClient(object):
msg = '{0} {1}'.format(response.status, data) msg = '{0} {1}'.format(response.status, data)
if data.startswith('Invalid Session TTL'): if data.startswith('Invalid Session TTL'):
raise InvalidSessionTTL(msg) raise InvalidSessionTTL(msg)
elif data.startswith('invalid session'):
raise InvalidSession(msg)
else: else:
raise ConsulInternalError(msg) raise ConsulInternalError(msg)
return base.Response(response.status, response.headers, data) return base.Response(response.status, response.headers, data)
@@ -91,9 +98,16 @@ class HTTPClient(object):
data = '{' + ttl + '}' data = '{' + ttl + '}'
else: else:
data = data[:-1] + ', ' + ttl + '}' data = data[:-1] + ', ' + ttl + '}'
if isinstance(params, list): # starting from v1.1.0 python-consul switched from `dict` to `list` for params
params = {k: v for k, v in params}
kwargs = {'retries': 0, 'preload_content': False, 'body': data} kwargs = {'retries': 0, 'preload_content': False, 'body': data}
if method == 'get' and isinstance(params, dict) and 'index' in params: if method == 'get' and isinstance(params, dict) and 'index' in params:
kwargs['timeout'] = (float(params['wait'][:-1]) if 'wait' in params else 300) + 1 timeout = float(params['wait'][:-1]) if 'wait' in params else 300
# According to the documentation a small random amount of additional wait time is added to the
# supplied maximum wait time to spread out the wake up time of any concurrent requests. This adds
# up to wait / 16 additional time to the maximum duration. Since our goal is actually getting a
# response rather read timeout we will add to the timeout a sligtly bigger value.
kwargs['timeout'] = timeout + max(timeout/15.0, 1)
else: else:
kwargs['timeout'] = self._read_timeout kwargs['timeout'] = self._read_timeout
token = params.pop('token', self.token) if isinstance(params, dict) else self.token token = params.pop('token', self.token) if isinstance(params, dict) else self.token
@@ -108,7 +122,7 @@ class ConsulClient(base.Consul):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self._cert = kwargs.pop('cert', None) self._cert = kwargs.pop('cert', None)
self._ca_cert = kwargs.pop('ca_cert', None) self._ca_cert = kwargs.pop('ca_cert', None)
self._token = kwargs.get('token') self.token = kwargs.get('token')
super(ConsulClient, self).__init__(*args, **kwargs) super(ConsulClient, self).__init__(*args, **kwargs)
def connect(self, *args, **kwargs): def connect(self, *args, **kwargs):
@@ -117,10 +131,15 @@ class ConsulClient(base.Consul):
kwargs['cert'] = self._cert kwargs['cert'] = self._cert
if self._ca_cert: if self._ca_cert:
kwargs['ca_cert'] = self._ca_cert kwargs['ca_cert'] = self._ca_cert
if self._token: if self.token:
kwargs['token'] = self._token kwargs['token'] = self.token
return HTTPClient(**kwargs) return HTTPClient(**kwargs)
def reload_config(self, config):
self.http.token = self.token = config.get('token')
self.consistency = config.get('consistency', 'default')
self.dc = config.get('dc')
def catch_consul_errors(func): def catch_consul_errors(func):
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
@@ -131,6 +150,31 @@ def catch_consul_errors(func):
return wrapper return wrapper
def force_if_last_failed(func):
def wrapper(*args, **kwargs):
if wrapper.last_result is False:
kwargs['force'] = True
wrapper.last_result = func(*args, **kwargs)
return wrapper.last_result
wrapper.last_result = None
return wrapper
def service_name_from_scope_name(scope_name):
"""Translate scope name to service name which can be used in dns.
230 = 253 - len('replica.') - len('.service.consul')
"""
def replace_char(match):
c = match.group(0)
return '-' if c in '. _' else "u{:04d}".format(ord(c))
service_name = re.sub(r'[^a-z0-9\-]', replace_char, scope_name.lower())
return service_name[0:230]
class Consul(AbstractDCS): class Consul(AbstractDCS):
def __init__(self, config): def __init__(self, config):
@@ -142,7 +186,6 @@ class Consul(AbstractDCS):
retry_exceptions=(ConsulInternalError, HTTPException, retry_exceptions=(ConsulInternalError, HTTPException,
HTTPError, socket.error, socket.timeout)) HTTPError, socket.error, socket.timeout))
self._my_member_data = {}
kwargs = {} kwargs = {}
if 'url' in config: if 'url' in config:
r = urlparse(config['url']) r = urlparse(config['url'])
@@ -159,7 +202,7 @@ class Consul(AbstractDCS):
if config.get('key') and config.get('cert'): if config.get('key') and config.get('cert'):
config['cert'] = (config['cert'], config['key']) config['cert'] = (config['cert'], config['key'])
config_keys = ('host', 'port', 'token', 'scheme', 'cert', 'ca_cert', 'dc') config_keys = ('host', 'port', 'token', 'scheme', 'cert', 'ca_cert', 'dc', 'consistency')
kwargs = {p: config.get(p) for p in config_keys if config.get(p)} kwargs = {p: config.get(p) for p in config_keys if config.get(p)}
verify = config.get('verify') verify = config.get('verify')
@@ -173,6 +216,13 @@ class Consul(AbstractDCS):
self.set_ttl(config.get('ttl') or 30) self.set_ttl(config.get('ttl') or 30)
self._last_session_refresh = 0 self._last_session_refresh = 0
self.__session_checks = config.get('checks') self.__session_checks = config.get('checks')
self._register_service = config.get('register_service', False)
if self._register_service:
self._service_name = service_name_from_scope_name(self._scope)
if self._scope != self._service_name:
logger.warning('Using %s as consul service name instead of scope name %s', self._service_name,
self._scope)
self._service_check_interval = config.get('service_check_interval', '5s')
if not self._ctl: if not self._ctl:
self.create_session() self.create_session()
@@ -187,11 +237,19 @@ class Consul(AbstractDCS):
logger.info('waiting on consul') logger.info('waiting on consul')
time.sleep(5) time.sleep(5)
def reload_config(self, config):
super(Consul, self).reload_config(config)
self._client.reload_config(config.get('consul', {}))
def set_ttl(self, ttl): def set_ttl(self, ttl):
if self._client.http.set_ttl(ttl/2.0): # Consul multiplies the TTL by 2x if self._client.http.set_ttl(ttl/2.0): # Consul multiplies the TTL by 2x
self._session = None self._session = None
self.__do_not_watch = True self.__do_not_watch = True
@property
def ttl(self):
return self._client.http.ttl
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._client.http.set_read_timeout(retry_timeout) self._client.http.set_read_timeout(retry_timeout)
@@ -254,7 +312,7 @@ class Consul(AbstractDCS):
nodes = {} nodes = {}
for node in results: for node in results:
node['Value'] = (node['Value'] or b'').decode('utf-8') node['Value'] = (node['Value'] or b'').decode('utf-8')
nodes[os.path.relpath(node['Key'], path)] = node nodes[node['Key'][len(path):].lstrip('/')] = node
# get initialize flag # get initialize flag
initialize = nodes.get(self._INITIALIZE) initialize = nodes.get(self._INITIALIZE)
@@ -297,48 +355,111 @@ class Consul(AbstractDCS):
sync = nodes.get(self._SYNC) sync = nodes.get(self._SYNC)
sync = SyncState.from_node(sync and sync['ModifyIndex'], sync and sync['Value']) sync = SyncState.from_node(sync and sync['ModifyIndex'], sync and sync['Value'])
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history) return Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
except NotFound: except NotFound:
self._cluster = Cluster(None, None, None, None, [], None, None, None) return Cluster(None, None, None, None, [], None, None, None)
except Exception: except Exception:
logger.exception('get_cluster') logger.exception('get_cluster')
raise ConsulError('Consul is not responding properly') raise ConsulError('Consul is not responding properly')
def touch_member(self, data, ttl=None, permanent=False): @catch_consul_errors
def touch_member(self, data, permanent=False):
cluster = self.cluster cluster = self.cluster
member = cluster and cluster.get_member(self._name, fallback_to_leader=False) member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
create_member = not permanent and self.refresh_session() create_member = not permanent and self.refresh_session()
if member and (create_member or member.session != self._session): if member and (create_member or member.session != self._session):
try: self._client.kv.delete(self.member_path)
self._client.kv.delete(self.member_path) create_member = True
create_member = True
except Exception:
return False
if not create_member and member and deep_compare(data, self._my_member_data): if not create_member and member and deep_compare(data, member.data):
return True return True
try: try:
args = {} if permanent else {'acquire': self._session} args = {} if permanent else {'acquire': self._session}
self._client.kv.put(self.member_path, json.dumps(data, separators=(',', ':')), **args) self._client.kv.put(self.member_path, json.dumps(data, separators=(',', ':')), **args)
self._my_member_data = data if self._register_service:
self.update_service(not create_member and member and member.data or {}, data)
return True return True
except InvalidSession:
self._session = None
logger.error('Our session disappeared from Consul, can not "touch_member"')
except Exception: except Exception:
logger.exception('touch_member') logger.exception('touch_member')
return False return False
@catch_consul_errors @catch_consul_errors
def _do_attempt_to_acquire_leader(self, kwargs): def register_service(self, service_name, **kwargs):
return self.retry(self._client.kv.put, self.leader_path, self._name, **kwargs) logger.info('Register service %s, params %s', service_name, kwargs)
return self._client.agent.service.register(service_name, **kwargs)
@catch_consul_errors
def deregister_service(self, service_id):
logger.info('Deregister service %s', service_id)
# service_id can contain special characters, but is used as part of uri in deregister request
service_id = quote(service_id)
return self._client.agent.service.deregister(service_id)
def _update_service(self, data):
service_name = self._service_name
role = data['role'].replace('_', '-')
state = data['state']
api_parts = urlparse(data['api_url'])
api_parts = api_parts._replace(path='/{0}'.format(role))
conn_parts = urlparse(data['conn_url'])
check = base.Check.http(api_parts.geturl(), self._service_check_interval,
deregister='{0}s'.format(self._client.http.ttl * 10))
params = {
'service_id': '{0}/{1}'.format(self._scope, self._name),
'address': conn_parts.hostname,
'port': conn_parts.port,
'check': check,
'tags': [role]
}
if state == 'stopped':
return self.deregister_service(params['service_id'])
if role in ['master', 'replica', 'standby-leader']:
if state != 'running':
return
return self.register_service(service_name, **params)
logger.warning('Could not register service: unknown role type %s', role)
@force_if_last_failed
def update_service(self, old_data, new_data, force=False):
update = False
for key in ['role', 'api_url', 'conn_url', 'state']:
if key not in new_data:
logger.warning('Could not register service: not enough params in member data')
return
if old_data.get(key) != new_data[key]:
update = True
if force or update:
return self._update_service(new_data)
@catch_consul_errors
def _do_attempt_to_acquire_leader(self, permanent):
try:
kwargs = {} if permanent else {'acquire': self._session}
return self.retry(self._client.kv.put, self.leader_path, self._name, **kwargs)
except InvalidSession:
self._session = None
logger.error('Our session disappeared from Consul. Will try to get a new one and retry attempt')
self.refresh_session()
return self.retry(self._client.kv.put, self.leader_path, self._name, acquire=self._session)
def attempt_to_acquire_leader(self, permanent=False): def attempt_to_acquire_leader(self, permanent=False):
if not self._session and not permanent: if not self._session and not permanent:
self.refresh_session() self.refresh_session()
ret = self._do_attempt_to_acquire_leader({} if permanent else {'acquire': self._session}) ret = self._do_attempt_to_acquire_leader(permanent)
if not ret: if not ret:
logger.info('Could not take out TTL lock') logger.info('Could not take out TTL lock')
return ret return ret
def take_leader(self): def take_leader(self):
@@ -395,6 +516,7 @@ class Consul(AbstractDCS):
return self.retry(self._client.kv.delete, self.sync_path, cas=index) return self.retry(self._client.kv.delete, self.sync_path, cas=index)
def watch(self, leader_index, timeout): def watch(self, leader_index, timeout):
self._last_session_refresh = 0
if self.__do_not_watch: if self.__do_not_watch:
self.__do_not_watch = False self.__do_not_watch = False
return True return True
@@ -406,7 +528,7 @@ class Consul(AbstractDCS):
idx, _ = self._client.kv.get(self.leader_path, index=leader_index, wait=str(timeout) + 's') idx, _ = self._client.kv.get(self.leader_path, index=leader_index, wait=str(timeout) + 's')
return str(idx) != str(leader_index) return str(idx) != str(leader_index)
except (ConsulException, HTTPException, HTTPError, socket.error, socket.timeout): except (ConsulException, HTTPException, HTTPError, socket.error, socket.timeout):
logging.exception('watch') logger.exception('watch')
timeout = end_time - time.time() timeout = end_time - time.time()
+57 -48
View File
@@ -14,7 +14,7 @@ from dns.exception import DNSException
from dns import resolver from dns import resolver
from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState, TimelineHistory from patroni.dcs import AbstractDCS, ClusterConfig, Cluster, Failover, Leader, Member, SyncState, TimelineHistory
from patroni.exceptions import DCSError from patroni.exceptions import DCSError
from patroni.utils import Retry, RetryFailedError, split_host_port from patroni.utils import Retry, RetryFailedError, split_host_port, uri
from urllib3.exceptions import HTTPError, ReadTimeoutError from urllib3.exceptions import HTTPError, ReadTimeoutError
from requests.exceptions import RequestException from requests.exceptions import RequestException
from six.moves.queue import Queue from six.moves.queue import Queue
@@ -25,10 +25,6 @@ from threading import Thread
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def uri(protocol, host, port, endpoint=''):
return '{0}://{1}:{2}{3}'.format(protocol, host, port, endpoint)
class EtcdError(DCSError): class EtcdError(DCSError):
pass pass
@@ -87,9 +83,12 @@ class Client(etcd.Client):
args = {p: config.get(p) for p in ('host', 'port', 'protocol', 'use_proxies', 'username', 'password', args = {p: config.get(p) for p in ('host', 'port', 'protocol', 'use_proxies', 'username', 'password',
'cert', 'ca_cert') if config.get(p)} 'cert', 'ca_cert') if config.get(p)}
super(Client, self).__init__(read_timeout=config['retry_timeout'], **args) super(Client, self).__init__(read_timeout=config['retry_timeout'], **args)
# For some reason python3-etcd on debian and ubuntu are not based on the latest version
# Workaround for the case when https://github.com/jplana/python-etcd/pull/196 is not applied
self.http.connection_pool_kw.pop('ssl_version', None)
self._config = config self._config = config
self._load_machines_cache() self._load_machines_cache()
self._allow_reconnect = not self._use_proxies self._allow_reconnect = True
def _build_request_parameters(self): def _build_request_parameters(self):
kwargs = {'headers': self._get_headers(), 'redirect': self.allow_redirect} kwargs = {'headers': self._get_headers(), 'redirect': self.allow_redirect}
@@ -128,8 +127,11 @@ class Client(etcd.Client):
while True: while True:
try: try:
response = self.http.request(self._MGET, self._base_uri + self.version_prefix + '/machines', **kwargs) response = self.http.request(self._MGET, self._base_uri + self.version_prefix + '/machines', **kwargs)
machines = [n.strip() for n in self._handle_server_response(response).data.decode('utf-8').split(',')] data = self._handle_server_response(response).data.decode('utf-8')
machines = [m.strip() for m in data.split(',') if m.strip()]
logger.debug("Retrieved list of machines: %s", machines) logger.debug("Retrieved list of machines: %s", machines)
if not machines:
raise etcd.EtcdException
random.shuffle(machines) random.shuffle(machines)
for url in machines: for url in machines:
r = urlparse(url) r = urlparse(url)
@@ -186,10 +188,8 @@ class Client(etcd.Client):
# Update machines_cache if previous attempt of update has failed # Update machines_cache if previous attempt of update has failed
if self._update_machines_cache: if self._update_machines_cache:
self._load_machines_cache() self._load_machines_cache()
elif 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._machines_cache = self.machines self._refresh_machines_cache()
if self._base_uri in self._machines_cache:
self._machines_cache.remove(self._base_uri)
self._machines_cache_updated = time.time() self._machines_cache_updated = time.time()
kwargs.update(self._build_request_parameters()) kwargs.update(self._build_request_parameters())
@@ -206,12 +206,13 @@ class Client(etcd.Client):
if response is False: if response is False:
some_request_failed = True some_request_failed = True
if some_request_failed and not self._use_proxies: if some_request_failed:
self._machines_cache = self.machines self._refresh_machines_cache()
if self._base_uri in self._machines_cache: except etcd.EtcdConnectionFailed as e:
self._machines_cache.remove(self._base_uri) if isinstance(e, etcd.EtcdWatchTimedOut) and self._machines_cache:
except etcd.EtcdConnectionFailed: self._base_uri = self._next_server()
self._update_machines_cache = True else:
self._update_machines_cache = True
if not response: if not response:
raise raise
return self._handle_server_response(response) return self._handle_server_response(response)
@@ -233,7 +234,7 @@ class Client(etcd.Client):
protocol = 'https' if '-ssl' in r else 'http' protocol = 'https' if '-ssl' in r else 'http'
endpoint = '/members' if '-server' in r else '' endpoint = '/members' if '-server' in r else ''
for host, port in self.get_srv_record('_etcd{0}._tcp.{1}'.format(r, srv)): for host, port in self.get_srv_record('_etcd{0}._tcp.{1}'.format(r, srv)):
url = uri(protocol, host, port, endpoint) url = uri(protocol, (host, port), endpoint)
if endpoint: if endpoint:
try: try:
response = requests.get(url, timeout=self.read_timeout, verify=False) response = requests.get(url, timeout=self.read_timeout, verify=False)
@@ -255,15 +256,25 @@ class Client(etcd.Client):
def _get_machines_cache_from_dns(self, host, port): def _get_machines_cache_from_dns(self, host, port):
"""One host might be resolved into multiple ip addresses. We will make list out of it""" """One host might be resolved into multiple ip addresses. We will make list out of it"""
if self.protocol == 'http': if self.protocol == 'http':
ret = [] ret = map(lambda res: uri(self.protocol, res[-1][:2]), self._dns_resolver.resolve(host, port))
for af, _, _, _, sa in self._dns_resolver.resolve(host, port):
host, port = sa[:2]
if af == socket.AF_INET6:
host = '[{0}]'.format(host)
ret.append(uri(self.protocol, host, port))
if ret: if ret:
return list(set(ret)) return list(set(ret))
return [uri(self.protocol, host, port)] return [uri(self.protocol, (host, port))]
def _get_machines_cache_from_config(self):
if 'proxy' in self._config:
return [uri(self.protocol, (self._config['host'], self._config['port']))]
machines_cache = []
if 'srv' in self._config:
machines_cache = self._get_machines_cache_from_srv(self._config['srv'])
if not machines_cache and 'hosts' in self._config:
machines_cache = list(self._config['hosts'])
if not machines_cache and 'host' in self._config:
machines_cache = self._get_machines_cache_from_dns(self._config['host'], self._config['port'])
return machines_cache
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.
@@ -276,19 +287,7 @@ 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')
if self._use_proxies: self._machines_cache = self._get_machines_cache_from_config()
self._machines_cache = [uri(self.protocol, self._config['host'], self._config['port'])]
else:
self._machines_cache = []
if 'srv' in self._config:
self._machines_cache = self._get_machines_cache_from_srv(self._config['srv'])
if not self._machines_cache and 'hosts' in self._config:
self._machines_cache = list(self._config['hosts'])
if not self._machines_cache and 'host' in self._config:
self._machines_cache = self._get_machines_cache_from_dns(self._config['host'], self._config['port'])
# 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 self._machines_cache:
@@ -296,14 +295,16 @@ class Client(etcd.Client):
# After filling up initial list of machines_cache we should ask etcd-cluster about actual list # After filling up initial list of machines_cache we should ask etcd-cluster about actual list
self._base_uri = self._next_server() self._base_uri = self._next_server()
self._machines_cache = self.machines self._refresh_machines_cache()
if self._base_uri in self._machines_cache:
self._machines_cache.remove(self._base_uri)
self._update_machines_cache = False self._update_machines_cache = False
self._machines_cache_updated = time.time() self._machines_cache_updated = time.time()
def _refresh_machines_cache(self):
self._machines_cache = self._get_machines_cache_from_config() if self._use_proxies else self.machines
if self._base_uri in self._machines_cache:
self._machines_cache.remove(self._base_uri)
class Etcd(AbstractDCS): class Etcd(AbstractDCS):
@@ -367,7 +368,7 @@ class Etcd(AbstractDCS):
config['hosts'] = [] config['hosts'] = []
for value in hosts: for value in hosts:
if isinstance(value, six.string_types): if isinstance(value, six.string_types):
config['hosts'].append(uri(protocol, *split_host_port(value, default_port))) config['hosts'].append(uri(protocol, split_host_port(value, default_port)))
elif 'host' in config: elif 'host' in config:
host, port = split_host_port(config['host'], 2379) host, port = split_host_port(config['host'], 2379)
config['host'] = host config['host'] = host
@@ -423,6 +424,8 @@ class Etcd(AbstractDCS):
while not client: while not client:
try: try:
client = Client(config, dns_resolver) client = Client(config, dns_resolver)
if 'use_proxies' in config and not client.machines:
raise etcd.EtcdException
except etcd.EtcdException: except etcd.EtcdException:
logger.info('waiting on etcd') logger.info('waiting on etcd')
time.sleep(5) time.sleep(5)
@@ -434,6 +437,10 @@ class Etcd(AbstractDCS):
self._ttl = ttl self._ttl = ttl
self._client.set_machines_cache_ttl(ttl*10) self._client.set_machines_cache_ttl(ttl*10)
@property
def ttl(self):
return self._ttl
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._client.set_read_timeout(retry_timeout) self._client.set_read_timeout(retry_timeout)
@@ -443,9 +450,10 @@ class Etcd(AbstractDCS):
return Member.from_node(node.modifiedIndex, os.path.basename(node.key), node.ttl, node.value) return Member.from_node(node.modifiedIndex, os.path.basename(node.key), node.ttl, node.value)
def _load_cluster(self): def _load_cluster(self):
cluster = None
try: try:
result = self.retry(self._client.read, self.client_path(''), recursive=True) result = self.retry(self._client.read, self.client_path(''), recursive=True)
nodes = {os.path.relpath(node.key, result.key): node for node in result.leaves} nodes = {node.key[len(result.key):].lstrip('/'): node for node in result.leaves}
# get initialize flag # get initialize flag
initialize = nodes.get(self._INITIALIZE) initialize = nodes.get(self._INITIALIZE)
@@ -483,17 +491,18 @@ class Etcd(AbstractDCS):
sync = nodes.get(self._SYNC) sync = nodes.get(self._SYNC)
sync = SyncState.from_node(sync and sync.modifiedIndex, sync and sync.value) sync = SyncState.from_node(sync and sync.modifiedIndex, sync and sync.value)
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history) cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
except etcd.EtcdKeyNotFound: except etcd.EtcdKeyNotFound:
self._cluster = Cluster(None, None, None, None, [], None, None, None) cluster = Cluster(None, None, None, None, [], None, None, None)
except Exception as e: except Exception as e:
self._handle_exception(e, 'get_cluster', raise_ex=EtcdError('Etcd is not responding properly')) self._handle_exception(e, 'get_cluster', raise_ex=EtcdError('Etcd is not responding properly'))
self._has_failed = False self._has_failed = False
return cluster
@catch_etcd_errors @catch_etcd_errors
def touch_member(self, data, ttl=None, permanent=False): def touch_member(self, data, permanent=False):
data = json.dumps(data, separators=(',', ':')) data = json.dumps(data, separators=(',', ':'))
return self.retry(self._client.set, self.member_path, data, None if permanent else ttl or self._ttl) return self._client.set(self.member_path, data, None if permanent else self._ttl)
@catch_etcd_errors @catch_etcd_errors
def take_leader(self): def take_leader(self):
+2 -2
View File
@@ -4,6 +4,7 @@ import requests
import time import time
from patroni.dcs.zookeeper import ZooKeeper from patroni.dcs.zookeeper import ZooKeeper
from patroni.utils import uri
from requests.exceptions import RequestException from requests.exceptions import RequestException
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -46,9 +47,8 @@ class ExhibitorEnsembleProvider(object):
def _query_exhibitors(self, exhibitors): def _query_exhibitors(self, exhibitors):
random.shuffle(exhibitors) random.shuffle(exhibitors)
for host in exhibitors: for host in exhibitors:
uri = 'http://{0}:{1}{2}'.format(host, self._exhibitor_port, self._uri_path)
try: try:
response = requests.get(uri, timeout=self.TIMEOUT) response = requests.get(uri('http', (host, self._exhibitor_port), self._uri_path), timeout=self.TIMEOUT)
return response.json() return response.json()
except RequestException: except RequestException:
pass pass
+48 -16
View File
@@ -92,13 +92,14 @@ class Kubernetes(AbstractDCS):
self.__subsets = None self.__subsets = None
use_endpoints = config.get('use_endpoints') and (config.get('patronictl') or 'pod_ip' in config) use_endpoints = config.get('use_endpoints') and (config.get('patronictl') or 'pod_ip' in config)
if use_endpoints: if use_endpoints:
addresses = [k8s_client.V1EndpointAddress(ip=config['pod_ip'])] addresses = [k8s_client.V1EndpointAddress(ip='127.0.0.1' if config.get('patronictl') else config['pod_ip'])]
ports = [] ports = []
for p in config.get('ports', [{}]): for p in config.get('ports', [{}]):
port = {'port': int(p.get('port', '5432'))} port = {'port': int(p.get('port', '5432'))}
port.update({n: p[n] for n in ('name', 'protocol') if p.get(n)}) port.update({n: p[n] for n in ('name', 'protocol') if p.get(n)})
ports.append(k8s_client.V1EndpointPort(**port)) ports.append(k8s_client.V1EndpointPort(**port))
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._api = CoreV1ApiProxy(use_endpoints) self._api = CoreV1ApiProxy(use_endpoints)
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)
@@ -106,6 +107,7 @@ class Kubernetes(AbstractDCS):
self._leader_observed_time = None self._leader_observed_time = None
self._leader_resource_version = None self._leader_resource_version = None
self._leader_observed_subsets = [] self._leader_observed_subsets = []
self._config_resource_version = None
self.__do_not_watch = False self.__do_not_watch = False
def retry(self, *args, **kwargs): def retry(self, *args, **kwargs):
@@ -123,6 +125,10 @@ class Kubernetes(AbstractDCS):
self.__do_not_watch = self._ttl != ttl self.__do_not_watch = self._ttl != ttl
self._ttl = ttl self._ttl = ttl
@property
def ttl(self):
return self._ttl
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) self._api.set_timeout(retry_timeout)
@@ -145,6 +151,7 @@ class Kubernetes(AbstractDCS):
config = nodes.get(self.config_path) config = nodes.get(self.config_path)
metadata = config and config.metadata metadata = config and config.metadata
self._config_resource_version = metadata.resource_version if metadata else None
annotations = metadata and metadata.annotations or {} annotations = metadata and metadata.annotations or {}
# get initialize flag # get initialize flag
@@ -152,7 +159,8 @@ class Kubernetes(AbstractDCS):
# get global dynamic configuration # get global dynamic configuration
config = ClusterConfig.from_node(metadata and metadata.resource_version, config = ClusterConfig.from_node(metadata and metadata.resource_version,
annotations.get(self._CONFIG) or '{}') annotations.get(self._CONFIG) or '{}',
metadata.resource_version if self._CONFIG in annotations else 0)
# get timeline history # get timeline history
history = TimelineHistory.from_node(metadata and metadata.resource_version, history = TimelineHistory.from_node(metadata and metadata.resource_version,
@@ -161,7 +169,7 @@ class Kubernetes(AbstractDCS):
leader = nodes.get(self.leader_path) leader = nodes.get(self.leader_path)
metadata = leader and leader.metadata metadata = leader and leader.metadata
self._leader_resource_version = metadata.resource_version if metadata else None self._leader_resource_version = metadata.resource_version if metadata else None
self._leader_observed_subsets = leader.subsets if self.__subsets and leader else [] self._leader_observed_subsets = leader.subsets if self.__subsets and leader and leader.subsets else []
annotations = metadata and metadata.annotations or {} annotations = metadata and metadata.annotations or {}
# get last leader operation # get last leader operation
@@ -199,7 +207,7 @@ class Kubernetes(AbstractDCS):
metadata = sync and sync.metadata metadata = sync and sync.metadata
sync = SyncState.from_node(metadata and metadata.resource_version, metadata and metadata.annotations) sync = SyncState.from_node(metadata and metadata.resource_version, metadata and metadata.annotations)
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history) return Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
except Exception: except Exception:
logger.exception('get_cluster') logger.exception('get_cluster')
raise KubernetesError('Kubernetes API is not responding properly') raise KubernetesError('Kubernetes API is not responding properly')
@@ -273,13 +281,34 @@ class Kubernetes(AbstractDCS):
body = k8s_client.V1ConfigMap(metadata=metadata) body = k8s_client.V1ConfigMap(metadata=metadata)
return self.retry(func, self._namespace, body) if retry else func(self._namespace, body) return self.retry(func, self._namespace, body) if retry else func(self._namespace, body)
def patch_or_create_config(self, annotations, resource_version=None, patch=False, retry=True):
# SCOPE-config endpoint requires corresponding service otherwise it might be "cleaned" by k8s master
if self.__subsets and not patch and not resource_version:
self._should_create_config_service = True
self._create_config_service()
ret = self.patch_or_create(self.config_path, annotations, resource_version, patch, retry)
if ret:
self._config_resource_version = ret.metadata.resource_version
return ret
def _create_config_service(self):
metadata = k8s_client.V1ObjectMeta(namespace=self._namespace, name=self.config_path, labels=self._labels)
body = k8s_client.V1Service(metadata=metadata, spec=k8s_client.V1ServiceSpec(cluster_ip='None'))
try:
if not self._api.create_namespaced_service(self._namespace, body):
return
except Exception as e:
if not isinstance(e, k8s_client.rest.ApiException) or e.status != 409: # Service already exists
return logger.exception('create_config_service failed')
self._should_create_config_service = False
def _write_leader_optime(self, last_operation): def _write_leader_optime(self, last_operation):
"""Unused""" """Unused"""
def _update_leader(self): def _update_leader(self):
"""Unused""" """Unused"""
def update_leader(self, last_operation): def update_leader(self, last_operation, access_is_restricted=False):
now = datetime.datetime.now(tzutc).isoformat() now = datetime.datetime.now(tzutc).isoformat()
annotations = {self._LEADER: self._name, 'ttl': str(self._ttl), 'renewTime': now, annotations = {self._LEADER: self._name, 'ttl': str(self._ttl), 'renewTime': now,
'acquireTime': self._leader_observed_record.get('acquireTime') or now, 'acquireTime': self._leader_observed_record.get('acquireTime') or now,
@@ -287,7 +316,9 @@ class Kubernetes(AbstractDCS):
if last_operation: if last_operation:
annotations[self._OPTIME] = last_operation annotations[self._OPTIME] = last_operation
ret = self.patch_or_create(self.leader_path, annotations, self._leader_resource_version, subsets=self.__subsets) subsets = [] if access_is_restricted else self.__subsets
ret = self.patch_or_create(self.leader_path, annotations, self._leader_resource_version, subsets=subsets)
if ret: if ret:
self._leader_resource_version = ret.metadata.resource_version self._leader_resource_version = ret.metadata.resource_version
return ret return ret
@@ -307,7 +338,8 @@ class Kubernetes(AbstractDCS):
else: else:
annotations['acquireTime'] = self._leader_observed_record.get('acquireTime') or now annotations['acquireTime'] = self._leader_observed_record.get('acquireTime') or now
annotations['transitions'] = str(transitions) annotations['transitions'] = str(transitions)
ret = self.patch_or_create(self.leader_path, annotations, self._leader_resource_version, subsets=self.__subsets) subsets = [] if self.__subsets else None
ret = self.patch_or_create(self.leader_path, annotations, self._leader_resource_version, subsets=subsets)
if ret: if ret:
self._leader_resource_version = ret.metadata.resource_version self._leader_resource_version = ret.metadata.resource_version
else: else:
@@ -326,14 +358,13 @@ class Kubernetes(AbstractDCS):
return self.patch_or_create(self.failover_path, annotations, index, bool(index or patch), False) return self.patch_or_create(self.failover_path, annotations, index, bool(index or patch), False)
def set_config_value(self, value, index=None): def set_config_value(self, value, index=None):
patch = bool(index or self.cluster and self.cluster.config and self.cluster.config.index) return self.patch_or_create_config({self._CONFIG: value}, index, bool(self._config_resource_version), False)
return self.patch_or_create(self.config_path, {self._CONFIG: value}, index, patch, False)
@catch_kubernetes_errors @catch_kubernetes_errors
def touch_member(self, data, ttl=None, permanent=False): def touch_member(self, data, permanent=False):
cluster = self.cluster cluster = self.cluster
if cluster and cluster.leader and cluster.leader.name == self._name: if cluster and cluster.leader and cluster.leader.name == self._name:
role = 'master' role = 'promoted' if data['role'] in ('replica', 'promoted') else 'master'
elif data['state'] == 'running' and data['role'] != 'master': elif data['state'] == 'running' and data['role'] != 'master':
role = data['role'] role = data['role']
else: else:
@@ -348,12 +379,14 @@ class Kubernetes(AbstractDCS):
'annotations': {'status': json.dumps(data, separators=(',', ':'))}} 'annotations': {'status': json.dumps(data, separators=(',', ':'))}}
body = k8s_client.V1Pod(metadata=k8s_client.V1ObjectMeta(**metadata)) body = k8s_client.V1Pod(metadata=k8s_client.V1ObjectMeta(**metadata))
ret = self._api.patch_namespaced_pod(self._name, self._namespace, body) ret = self._api.patch_namespaced_pod(self._name, self._namespace, body)
if self.__subsets and self._should_create_config_service:
self._create_config_service()
return ret return ret
def initialize(self, create_new=True, sysid=""): def initialize(self, create_new=True, sysid=""):
cluster = self.cluster cluster = self.cluster
resource_version = cluster.config.index if cluster and cluster.config and cluster.config.index else None resource_version = cluster.config.index if cluster and cluster.config and cluster.config.index else None
return self.patch_or_create(self.config_path, {self._INITIALIZE: sysid}, resource_version) return self.patch_or_create_config({self._INITIALIZE: sysid}, resource_version)
def delete_leader(self): def delete_leader(self):
if self.cluster and isinstance(self.cluster.leader, Leader) and self.cluster.leader.name == self._name: if self.cluster and isinstance(self.cluster.leader, Leader) and self.cluster.leader.name == self._name:
@@ -361,15 +394,14 @@ class Kubernetes(AbstractDCS):
self.reset_cluster() self.reset_cluster()
def cancel_initialization(self): def cancel_initialization(self):
self.patch_or_create(self.config_path, {self._INITIALIZE: None}, self.cluster.config.index, True) self.patch_or_create_config({self._INITIALIZE: None}, self._config_resource_version, True)
@catch_kubernetes_errors @catch_kubernetes_errors
def delete_cluster(self): def delete_cluster(self):
self.retry(self._api.delete_collection_namespaced_kind, self._namespace, label_selector=self._label_selector) self.retry(self._api.delete_collection_namespaced_kind, self._namespace, label_selector=self._label_selector)
def set_history_value(self, value): def set_history_value(self, value):
patch = bool(self.cluster and self.cluster.config and self.cluster.config.index) return self.patch_or_create_config({self._HISTORY: value}, None, bool(self._config_resource_version), False)
return self.patch_or_create(self.config_path, {self._HISTORY: value}, None, patch, False)
def set_sync_state_value(self, value, index=None): def set_sync_state_value(self, value, index=None):
"""Unused""" """Unused"""
@@ -399,7 +431,7 @@ class Kubernetes(AbstractDCS):
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
except Exception: except Exception:
logging.exception('watch') logger.exception('watch')
timeout = end_time - time.time() timeout = end_time - time.time()
+56 -49
View File
@@ -1,5 +1,6 @@
import json import json
import logging import logging
import select
import time import time
from kazoo.client import KazooClient, KazooState, KazooRetry from kazoo.client import KazooClient, KazooState, KazooRetry
@@ -37,12 +38,21 @@ class PatroniSequentialThreadingHandler(SequentialThreadingHandler):
`connect_timeout` (negotiated session timeout) as the second element.""" `connect_timeout` (negotiated session timeout) as the second element."""
args = list(args) args = list(args)
if len(args) == 1: if len(args) == 0: # kazoo 2.6.0 slightly changed the way how it calls create_connection method
kwargs['timeout'] = max(self._connect_timeout, kwargs.get('timeout', self._connect_timeout*10)/10.0)
elif len(args) == 1:
args.append(self._connect_timeout) args.append(self._connect_timeout)
else: else:
args[1] = max(self._connect_timeout, args[1]/10.0) args[1] = max(self._connect_timeout, args[1]/10.0)
return super(PatroniSequentialThreadingHandler, self).create_connection(*args, **kwargs) return super(PatroniSequentialThreadingHandler, self).create_connection(*args, **kwargs)
def select(self, *args, **kwargs):
"""Python3 raises `ValueError` if socket is closed, because fd == -1"""
try:
return super(PatroniSequentialThreadingHandler, self).select(*args, **kwargs)
except ValueError as e:
raise select.error(9, str(e))
class ZooKeeper(AbstractDCS): class ZooKeeper(AbstractDCS):
@@ -59,7 +69,6 @@ class ZooKeeper(AbstractDCS):
max_delay=1, max_tries=-1, sleep_func=time.sleep)) max_delay=1, max_tries=-1, sleep_func=time.sleep))
self._client.add_listener(self.session_listener) self._client.add_listener(self.session_listener)
self._my_member_data = {}
self._fetch_cluster = True self._fetch_cluster = True
self._orig_kazoo_connect = self._client._connection._connect self._orig_kazoo_connect = self._client._connection._connect
@@ -117,6 +126,10 @@ class ZooKeeper(AbstractDCS):
self._client.restart() self._client.restart()
return True return True
@property
def ttl(self):
return self._client._session_timeout
def set_retry_timeout(self, retry_timeout): def set_retry_timeout(self, retry_timeout):
retry = self._client.retry if isinstance(self._client.retry, KazooRetry) else self._client._retry retry = self._client.retry if isinstance(self._client.retry, KazooRetry) else self._client._retry
retry.deadline = retry_timeout retry.deadline = retry_timeout
@@ -197,62 +210,74 @@ class ZooKeeper(AbstractDCS):
failover = self.get_node(self.failover_path, watch=self.cluster_watcher) if self._FAILOVER in nodes else None failover = self.get_node(self.failover_path, watch=self.cluster_watcher) if self._FAILOVER in nodes else None
failover = failover and Failover.from_node(failover[1].version, failover[0]) failover = failover and Failover.from_node(failover[1].version, failover[0])
self._cluster = Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history) return Cluster(initialize, config, leader, last_leader_operation, members, failover, sync, history)
def _load_cluster(self): def _load_cluster(self):
if self._fetch_cluster or self._cluster is None: cluster = self.cluster
if self._fetch_cluster or cluster is None:
try: try:
self._client.retry(self._inner_load_cluster) cluster = self._client.retry(self._inner_load_cluster)
except Exception: except Exception:
logger.exception('get_cluster') logger.exception('get_cluster')
self.cluster_watcher(None) self.cluster_watcher(None)
raise ZooKeeperError('ZooKeeper in not responding properly') raise ZooKeeperError('ZooKeeper in not responding properly')
return cluster
def _create(self, path, value, **kwargs): def _create(self, path, value, retry=False, ephemeral=False):
try: try:
self._client.retry(self._client.create, path, value.encode('utf-8'), **kwargs) if retry:
self._client.retry(self._client.create, path, value, makepath=True, ephemeral=ephemeral)
else:
self._client.create_async(path, value, makepath=True, ephemeral=ephemeral).get(timeout=1)
return True return True
except Exception: except Exception:
return False logger.exception('Failed to create %s', path)
return False
def attempt_to_acquire_leader(self, permanent=False): def attempt_to_acquire_leader(self, permanent=False):
ret = self._create(self.leader_path, self._name, makepath=True, ephemeral=not permanent) ret = self._create(self.leader_path, self._name.encode('utf-8'), retry=True, ephemeral=not permanent)
if not ret: if not ret:
logger.info('Could not take out TTL lock') logger.info('Could not take out TTL lock')
return ret return ret
def __set_failover_or_sync_state_value(self, key, value, index=None): def _set_or_create(self, key, value, index=None, retry=False, do_not_create_empty=False):
value = value.encode('utf-8')
try: try:
self._client.retry(self._client.set, key, value.encode('utf-8'), version=index or -1) if retry:
self._client.retry(self._client.set, key, value, version=index or -1)
else:
self._client.set_async(key, value, version=index or -1).get(timeout=1)
return True return True
except NoNodeError: except NoNodeError:
return value == '' or (index is None and self._create(key, value)) if do_not_create_empty and not value:
return True
elif index is None:
return self._create(key, value, retry)
else:
return False
except Exception: except Exception:
logging.exception('set_failover_value') logger.exception('Failed to update %s', key)
return False return False
def set_failover_value(self, value, index=None): def set_failover_value(self, value, index=None):
return self.__set_failover_or_sync_state_value(self.failover_path, value, index) return self._set_or_create(self.failover_path, value, index)
def set_config_value(self, value, index=None): def set_config_value(self, value, index=None):
try: return self._set_or_create(self.config_path, value, index, retry=True)
self._client.retry(self._client.set, self.config_path, value.encode('utf-8'), version=index or -1)
return True
except NoNodeError:
return index is None and self._create(self.config_path, value)
except Exception:
logging.exception('set_config_value')
return False
def initialize(self, create_new=True, sysid=""): def initialize(self, create_new=True, sysid=""):
return self._create(self.initialize_path, sysid, makepath=True) if create_new \ sysid = sysid.encode('utf-8')
else self._client.retry(self._client.set, self.initialize_path, sysid.encode("utf-8")) return self._create(self.initialize_path, sysid, retry=True) if create_new \
else self._client.retry(self._client.set, self.initialize_path, sysid)
def touch_member(self, data, ttl=None, permanent=False): def touch_member(self, data, permanent=False):
cluster = self.cluster cluster = self.cluster
member = cluster and cluster.get_member(self._name, fallback_to_leader=False) member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
encoded_data = json.dumps(data, separators=(',', ':')).encode('utf-8') encoded_data = json.dumps(data, separators=(',', ':')).encode('utf-8')
if member and self._client.client_id is not None and member.session != self._client.client_id[0]: if member and (self._client.client_id is not None and member.session != self._client.client_id[0] or
not (deep_compare(member.data.get('tags', {}), data.get('tags', {})) and
member.data.get('version') == data.get('version') and
member.data.get('checkpoint_after_promote') == data.get('checkpoint_after_promote'))):
try: try:
self._client.delete_async(self.member_path).get(timeout=1) self._client.delete_async(self.member_path).get(timeout=1)
except NoNodeError: except NoNodeError:
@@ -262,13 +287,12 @@ class ZooKeeper(AbstractDCS):
member = None member = None
if member: if member:
if deep_compare(data, self._my_member_data): if deep_compare(data, member.data):
return True return True
else: else:
try: try:
self._client.create_async(self.member_path, encoded_data, makepath=True, self._client.create_async(self.member_path, encoded_data, makepath=True,
ephemeral=not permanent).get(timeout=1) ephemeral=not permanent).get(timeout=1)
self._my_member_data = data
return True return True
except Exception as e: except Exception as e:
if not isinstance(e, NodeExistsError): if not isinstance(e, NodeExistsError):
@@ -276,7 +300,6 @@ class ZooKeeper(AbstractDCS):
return False return False
try: try:
self._client.set_async(self.member_path, encoded_data).get(timeout=1) self._client.set_async(self.member_path, encoded_data).get(timeout=1)
self._my_member_data = data
return True return True
except Exception: except Exception:
logger.exception('touch_member') logger.exception('touch_member')
@@ -286,30 +309,14 @@ class ZooKeeper(AbstractDCS):
def take_leader(self): def take_leader(self):
return self.attempt_to_acquire_leader() return self.attempt_to_acquire_leader()
def __write_leader_optime_or_history_value(self, key, value):
value = value.encode('utf-8')
try:
self._client.set_async(key, value).get(timeout=1)
return True
except NoNodeError:
try:
self._client.create_async(key, value, makepath=True).get(timeout=1)
return True
except Exception:
logger.exception('Failed to create %s', key)
except Exception:
logger.exception('Failed to update %s', key)
return False
def _write_leader_optime(self, last_operation): def _write_leader_optime(self, last_operation):
return self.__write_leader_optime_or_history_value(self.leader_optime_path, last_operation) return self._set_or_create(self.leader_optime_path, last_operation)
def _update_leader(self): def _update_leader(self):
return True return True
def delete_leader(self): def delete_leader(self):
self._client.restart() self._client.restart()
self._my_member_data = None
return True return True
def _cancel_initialization(self): def _cancel_initialization(self):
@@ -330,10 +337,10 @@ class ZooKeeper(AbstractDCS):
return True return True
def set_history_value(self, value): def set_history_value(self, value):
return self.__write_leader_optime_or_history_value(self.history_path, value) return self._set_or_create(self.history_path, value)
def set_sync_state_value(self, value, index=None): def set_sync_state_value(self, value, index=None):
return self.__set_failover_or_sync_state_value(self.sync_path, value, index) return self._set_or_create(self.sync_path, value, index, retry=True, do_not_create_empty=True)
def delete_sync_state(self, index=None): def delete_sync_state(self, index=None):
return self.set_sync_state_value("{}", index) return self.set_sync_state_value("{}", index)
+331 -100
View File
@@ -6,37 +6,44 @@ import psycopg2
import requests import requests
import sys import sys
import time import time
import uuid
from collections import namedtuple from collections import namedtuple
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
from patroni.async_executor import AsyncExecutor, CriticalTask from patroni.async_executor import AsyncExecutor, CriticalTask
from patroni.exceptions import DCSError, PostgresConnectionException, PatroniException from patroni.exceptions import DCSError, PostgresConnectionException, PatroniException
from patroni.postgresql import ACTION_ON_START from patroni.postgresql import ACTION_ON_START, ACTION_ON_ROLE_CHANGE
from patroni.postgresql.misc import postgres_version_to_int
from patroni.postgresql.rewind import Rewind
from patroni.utils import polling_loop, tzutc from patroni.utils import polling_loop, tzutc
from patroni.dcs import RemoteMember
from threading import RLock from threading import RLock
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class _MemberStatus(namedtuple('_MemberStatus', 'member,reachable,in_recovery,wal_position,tags,watchdog_failed')): class _MemberStatus(namedtuple('_MemberStatus', ['member', 'reachable', 'in_recovery', 'timeline',
'wal_position', 'tags', 'watchdog_failed'])):
"""Node status distilled from API response: """Node status distilled from API response:
member - dcs.Member object of the node member - dcs.Member object of the node
reachable - `!False` if the node is not reachable or is not responding with correct JSON reachable - `!False` if the node is not reachable or is not responding with correct JSON
in_recovery - `!True` if pg_is_in_recovery() == true in_recovery - `!True` if pg_is_in_recovery() == true
wal_position - value of `replayed_location` or `location` from JSON, dependin on its role. timeline - timeline value from JSON
wal_position - maximum value of `replayed_location` or `received_location` from JSON
tags - dictionary with values of different tags (i.e. nofailover) tags - dictionary with values of different tags (i.e. nofailover)
watchdog_failed - indicates that watchdog is required by configuration but not available or failed watchdog_failed - indicates that watchdog is required by configuration but not available or failed
""" """
@classmethod @classmethod
def from_api_response(cls, member, json): def from_api_response(cls, member, json):
is_master = json['role'] == 'master' is_master = json['role'] == 'master'
timeline = json.get('timeline', 0)
wal = not is_master and max(json['xlog'].get('received_location', 0), json['xlog'].get('replayed_location', 0)) wal = not is_master and max(json['xlog'].get('received_location', 0), json['xlog'].get('replayed_location', 0))
return cls(member, True, not is_master, wal, json.get('tags', {}), json.get('watchdog_failed', False)) return cls(member, True, not is_master, timeline, wal, json.get('tags', {}), json.get('watchdog_failed', False))
@classmethod @classmethod
def unknown(cls, member): def unknown(cls, member):
return cls(member, False, None, 0, {}, False) return cls(member, False, None, 0, 0, {}, False)
def failover_limitation(self): def failover_limitation(self):
"""Returns reason why this node can't promote or None if everything is ok.""" """Returns reason why this node can't promote or None if everything is ok."""
@@ -54,15 +61,20 @@ class Ha(object):
def __init__(self, patroni): def __init__(self, patroni):
self.patroni = patroni self.patroni = patroni
self.state_handler = patroni.postgresql self.state_handler = patroni.postgresql
self._rewind = Rewind(self.state_handler)
self.dcs = patroni.dcs self.dcs = patroni.dcs
self.cluster = None self.cluster = None
self.old_cluster = None self.old_cluster = None
self._is_leader = False
self._is_leader_lock = RLock()
self._leader_access_is_restricted = False
self._was_paused = False
self._leader_timeline = None self._leader_timeline = None
self.recovering = False self.recovering = False
self._post_bootstrap_task = None self._post_bootstrap_task = None
self._crash_recovery_executed = False self._crash_recovery_executed = False
self._start_timeout = None self._start_timeout = None
self._async_executor = AsyncExecutor(self.state_handler, self.wakeup) self._async_executor = AsyncExecutor(self.state_handler.cancellable, self.wakeup)
self.watchdog = patroni.watchdog self.watchdog = patroni.watchdog
# Each member publishes various pieces of information to the DCS using touch_member. This lock protects # Each member publishes various pieces of information to the DCS using touch_member. This lock protects
@@ -72,8 +84,46 @@ class Ha(object):
# standby. Changes protected by _member_state_lock. # standby. Changes protected by _member_state_lock.
self._disable_sync = 0 self._disable_sync = 0
# We need following property to avoid shutdown of postgres when join of Patroni to the postgres
# already running as replica was aborted due to cluster not beeing initialized in DCS.
self._join_aborted = False
def check_mode(self, mode):
# Try to protect from the case when DCS was wiped out during pause
if self.cluster and self.cluster.config and self.cluster.config.modify_index:
return self.cluster.check_mode(mode)
else:
return self.patroni.config.check_mode(mode)
def is_paused(self): def is_paused(self):
return self.cluster and self.cluster.is_paused() return self.check_mode('pause')
def check_timeline(self):
return self.check_mode('check_timeline')
def get_standby_cluster_config(self):
if self.cluster and self.cluster.config and self.cluster.config.modify_index:
config = self.cluster.config.data
else:
config = self.patroni.config.dynamic_configuration
return config.get('standby_cluster')
def is_standby_cluster(self):
config = self.get_standby_cluster_config()
# Check whether or not provided configuration describes a standby cluster
return isinstance(config, dict) and (config.get('host') or config.get('port') or config.get('restore_command'))
def is_leader(self):
with self._is_leader_lock:
return self._is_leader > time.time() and not self._leader_access_is_restricted
def set_is_leader(self, value):
with self._is_leader_lock:
self._is_leader = time.time() + self.dcs.ttl if value else 0
def set_leader_access_is_restricted(self, value):
with self._is_leader_lock:
self._leader_access_is_restricted = value
def load_cluster_from_dcs(self): def load_cluster_from_dcs(self):
cluster = self.dcs.get_cluster() cluster = self.dcs.get_cluster()
@@ -83,10 +133,16 @@ class Ha(object):
self.old_cluster = cluster self.old_cluster = cluster
self.cluster = cluster self.cluster = cluster
if not self.has_lock(False):
self.set_is_leader(False)
self._leader_timeline = None if cluster.is_unlocked() else cluster.leader.timeline self._leader_timeline = None if cluster.is_unlocked() else cluster.leader.timeline
def acquire_lock(self): def acquire_lock(self):
return self.dcs.attempt_to_acquire_leader() self.set_leader_access_is_restricted(self.cluster.has_permanent_logical_slots(self.state_handler.name))
ret = self.dcs.attempt_to_acquire_leader()
self.set_is_leader(ret)
return ret
def update_lock(self, write_leader_optime=False): def update_lock(self, write_leader_optime=False):
last_operation = None last_operation = None
@@ -95,14 +151,16 @@ class Ha(object):
last_operation = self.state_handler.last_operation() last_operation = self.state_handler.last_operation()
except Exception: except Exception:
logger.exception('Exception when called state_handler.last_operation()') logger.exception('Exception when called state_handler.last_operation()')
ret = self.dcs.update_leader(last_operation) ret = self.dcs.update_leader(last_operation, self._leader_access_is_restricted)
self.set_is_leader(ret)
if ret: if ret:
self.watchdog.keepalive() self.watchdog.keepalive()
return ret return ret
def has_lock(self): def has_lock(self, info=True):
lock_owner = self.cluster.leader and self.cluster.leader.name lock_owner = self.cluster.leader and self.cluster.leader.name
logger.info('Lock owner: %s; I am %s', lock_owner, self.state_handler.name) if info:
logger.info('Lock owner: %s; I am %s', lock_owner, self.state_handler.name)
return lock_owner == self.state_handler.name return lock_owner == self.state_handler.name
def get_effective_tags(self): def get_effective_tags(self):
@@ -119,8 +177,15 @@ class Ha(object):
'conn_url': self.state_handler.connection_string, 'conn_url': self.state_handler.connection_string,
'api_url': self.patroni.api.connection_string, 'api_url': self.patroni.api.connection_string,
'state': self.state_handler.state, 'state': self.state_handler.state,
'role': self.state_handler.role 'role': self.state_handler.role,
'version': self.patroni.version
} }
# following two lines are mainly necessary for consul, to avoid creation of master service
if data['role'] == 'master' and not self.is_leader():
data['role'] = 'promoted'
if self.is_leader() and not self._rewind.checkpoint_after_promote():
data['checkpoint_after_promote'] = False
tags = self.get_effective_tags() tags = self.get_effective_tags()
if tags: if tags:
data['tags'] = tags data['tags'] = tags
@@ -148,7 +213,11 @@ class Ha(object):
return self.dcs.touch_member(data) return self.dcs.touch_member(data)
def clone(self, clone_member=None, msg='(without leader)'): def clone(self, clone_member=None, msg='(without leader)'):
if self.state_handler.clone(clone_member): if self.is_standby_cluster() and not isinstance(clone_member, RemoteMember):
clone_member = self.get_remote_member(clone_member)
self._rewind.reset_state()
if self.state_handler.bootstrap.clone(clone_member):
logger.info('bootstrapped %s', msg) logger.info('bootstrapped %s', msg)
cluster = self.dcs.get_cluster() cluster = self.dcs.get_cluster()
node_to_follow = self._get_node_to_follow(cluster) node_to_follow = self._get_node_to_follow(cluster)
@@ -165,34 +234,65 @@ class Ha(object):
self._async_executor.schedule('bootstrap {0}'.format(msg)) self._async_executor.schedule('bootstrap {0}'.format(msg))
self._async_executor.run_async(self.clone, args=(clone_member, msg)) self._async_executor.run_async(self.clone, args=(clone_member, msg))
return 'trying to bootstrap {0}'.format(msg) return 'trying to bootstrap {0}'.format(msg)
# no initialize key and node is allowed to be master and has 'bootstrap' section in a configuration file # no initialize key and node is allowed to be master and has 'bootstrap' section in a configuration file
elif self.cluster.initialize is None and not self.patroni.nofailover and 'bootstrap' in self.patroni.config: elif self.cluster.initialize is None and not self.patroni.nofailover and 'bootstrap' in self.patroni.config:
if self.dcs.initialize(create_new=True): # race for initialization if self.dcs.initialize(create_new=True): # race for initialization
self.state_handler.bootstrapping = True self.state_handler.bootstrapping = True
self._post_bootstrap_task = CriticalTask() self._post_bootstrap_task = CriticalTask()
self._async_executor.schedule('bootstrap')
self._async_executor.run_async(self.state_handler.bootstrap, args=(self.patroni.config['bootstrap'],)) if self.is_standby_cluster():
return 'trying to bootstrap a new cluster' self._async_executor.schedule('bootstrap_standby_leader')
self._async_executor.run_async(self.bootstrap_standby_leader)
return 'trying to bootstrap a new standby leader'
else:
self._async_executor.schedule('bootstrap')
self._async_executor.run_async(
self.state_handler.bootstrap.bootstrap,
args=(self.patroni.config['bootstrap'],)
)
return 'trying to bootstrap a new cluster'
else: else:
return 'failed to acquire initialize lock' return 'failed to acquire initialize lock'
else: else:
if self.state_handler.can_create_replica_without_replication_connection(): create_replica_methods = self.get_standby_cluster_config().get('create_replica_methods', []) \
if self.is_standby_cluster() else None
if self.state_handler.can_create_replica_without_replication_connection(create_replica_methods):
msg = 'bootstrap (without leader)' msg = 'bootstrap (without leader)'
self._async_executor.schedule(msg) self._async_executor.schedule(msg)
self._async_executor.run_async(self.clone) self._async_executor.run_async(self.clone)
return 'trying to ' + msg return 'trying to ' + msg
return 'waiting for leader to bootstrap' return 'waiting for {0}leader to bootstrap'.format('standby_' if self.is_standby_cluster() else '')
def _handle_rewind(self): def bootstrap_standby_leader(self):
if self.state_handler.rewind_needed_and_possible(self.cluster.leader): """ If we found 'standby' key in the configuration, we need to bootstrap
self._async_executor.schedule('running pg_rewind from ' + self.cluster.leader.name) not a real master, but a 'standby leader', that will take base backup
self._async_executor.run_async(self.state_handler.rewind, (self.cluster.leader,)) from a remote master and start follow it.
"""
clone_source = self.get_remote_master()
msg = 'clone from remote master {0}'.format(clone_source.conn_url)
result = self.clone(clone_source, msg)
self._post_bootstrap_task.complete(result)
if result:
self.state_handler.set_role('standby_leader')
return result
def _handle_rewind_or_reinitialize(self):
leader = self.get_remote_master() if self.is_standby_cluster() else self.cluster.leader
if not self._rewind.rewind_or_reinitialize_needed_and_possible(leader):
return None
if self._rewind.can_rewind:
self._async_executor.schedule('running pg_rewind from ' + leader.name)
self._async_executor.run_async(self._rewind.execute, (leader,))
return True return True
def _start_crash_recovery(self, msg): # remove_data_directory_on_diverged_timelines is set
self._async_executor.schedule(msg) if not self.is_standby_cluster():
self._async_executor.run_async(self.state_handler.fix_cluster_state) self._async_executor.schedule('reinitializing due to diverged timelines')
return msg self._async_executor.run_async(self._do_reinitialize, args=(self.cluster, ))
return True
def recover(self): def recover(self):
# Postgres is not running and we will restart in standby mode. Watchdog is not needed until we promote. # Postgres is not running and we will restart in standby mode. Watchdog is not needed until we promote.
@@ -214,44 +314,53 @@ class Ha(object):
timeout = None timeout = None
data = self.state_handler.controldata() data = self.state_handler.controldata()
if data.get('Database cluster state') == 'in production' and not self._crash_recovery_executed and \ logger.info('pg_controldata:\n%s\n', '\n'.join(' {0}: {1}'.format(k, v) for k, v in data.items()))
(self.cluster.is_unlocked() or self.state_handler.can_rewind): if data.get('Database cluster state') in ('in production', 'shutting down', 'in crash recovery') \
and not self._crash_recovery_executed and \
(self.cluster.is_unlocked() or self._rewind.can_rewind):
self._crash_recovery_executed = True self._crash_recovery_executed = True
return self._start_crash_recovery('doing crash recovery in a single user mode') self._async_executor.schedule('doing crash recovery in a single user mode')
self._async_executor.run_async(self.state_handler.fix_cluster_state)
return self._async_executor.scheduled_action
self.load_cluster_from_dcs() self.load_cluster_from_dcs()
if self.has_lock(): role = 'replica'
if self.is_standby_cluster() or not self.has_lock():
if not self._rewind.executed:
self._rewind.trigger_check_diverged_lsn()
if self._handle_rewind_or_reinitialize():
return self._async_executor.scheduled_action
if self.has_lock(): # in standby cluster
msg = "starting as a standby leader because i had the session lock"
role = 'standby_leader'
node_to_follow = self._get_node_to_follow(self.cluster)
elif self.is_standby_cluster() and self.cluster.is_unlocked():
msg = "trying to follow a remote master because standby cluster is unhealthy"
node_to_follow = self.get_remote_master()
else:
msg = "starting as a secondary"
node_to_follow = self._get_node_to_follow(self.cluster)
elif self.has_lock():
msg = "starting as readonly because i had the session lock" msg = "starting as readonly because i had the session lock"
node_to_follow = None node_to_follow = None
else:
if not self.state_handler.rewind_executed:
self.state_handler.trigger_check_diverged_lsn()
if self._handle_rewind():
return self._async_executor.scheduled_action
msg = "starting as a secondary"
node_to_follow = self._get_node_to_follow(self.cluster)
# once we already tried to start postgres but failed, single user mode is a rescue in this case
if self.recovering and not self.state_handler.rewind_executed \
and not self._crash_recovery_executed and self.state_handler.can_rewind \
and data.get('Database cluster state') not in ('shut down', 'shut down in recovery'):
self.recovering = False
return self._start_crash_recovery('fixing cluster state in a single user mode')
self.recovering = True self.recovering = True
self._async_executor.schedule('restarting after failure') self._async_executor.schedule('restarting after failure')
self._async_executor.run_async(self.state_handler.follow, (node_to_follow, timeout)) self._async_executor.run_async(self.state_handler.follow, (node_to_follow, role, timeout))
return msg return msg
def _get_node_to_follow(self, cluster): def _get_node_to_follow(self, cluster):
# determine the node to follow. If replicatefrom tag is set, # determine the node to follow. If replicatefrom tag is set,
# try to follow the node mentioned there, otherwise, follow the leader. # try to follow the node mentioned there, otherwise, follow the leader.
if not self.patroni.replicatefrom or self.patroni.replicatefrom == self.state_handler.name: if self.is_standby_cluster() and (self.cluster.is_unlocked() or self.has_lock(False)):
node_to_follow = cluster.leader node_to_follow = self.get_remote_master()
else: 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:
node_to_follow = cluster.leader
return node_to_follow if node_to_follow and node_to_follow.name != self.state_handler.name else None return node_to_follow if node_to_follow and node_to_follow.name != self.state_handler.name else None
@@ -264,7 +373,8 @@ class Ha(object):
node_to_follow = self._get_node_to_follow(self.cluster) node_to_follow = self._get_node_to_follow(self.cluster)
if self.is_paused(): if self.is_paused():
if not (self.state_handler.need_rewind and self.state_handler.can_rewind) or self.cluster.is_unlocked(): if not (self._rewind.is_needed and self._rewind.can_rewind_or_reinitialize_allowed)\
or self.cluster.is_unlocked():
self.state_handler.set_role('master' if is_leader else 'replica') self.state_handler.set_role('master' if is_leader else 'replica')
if is_leader: if is_leader:
return 'continue to run as master without lock' return 'continue to run as master without lock'
@@ -274,20 +384,28 @@ class Ha(object):
self.demote('immediate-nolock') self.demote('immediate-nolock')
return demote_reason return demote_reason
if self._handle_rewind(): if self._handle_rewind_or_reinitialize():
return self._async_executor.scheduled_action return self._async_executor.scheduled_action
if not self.state_handler.check_recovery_conf(node_to_follow): role = 'standby_leader' if isinstance(node_to_follow, RemoteMember) and self.has_lock(False) else 'replica'
# It might happen that leader key in the standby cluster references non-exiting member.
# In this case it is safe to continue running without changing recovery.conf
if self.is_standby_cluster() and role == 'replica' and not (node_to_follow and node_to_follow.conn_url):
return 'continue following the old known standby leader'
elif not self.state_handler.config.check_recovery_conf(node_to_follow):
self._async_executor.schedule('changing primary_conninfo and restarting') self._async_executor.schedule('changing primary_conninfo and restarting')
self._async_executor.run_async(self.state_handler.follow, (node_to_follow,)) self._async_executor.run_async(self.state_handler.follow, (node_to_follow, role))
elif role == 'standby_leader' and self.state_handler.role != role:
self.state_handler.set_role(role)
self.state_handler.call_nowait(ACTION_ON_ROLE_CHANGE)
return follow_reason return follow_reason
def is_synchronous_mode(self): def is_synchronous_mode(self):
return bool(self.cluster and self.cluster.is_synchronous_mode()) return self.check_mode('synchronous_mode')
def is_synchronous_mode_strict(self): def is_synchronous_mode_strict(self):
return bool(self.cluster and self.cluster.is_synchronous_mode_strict()) return self.check_mode('synchronous_mode_strict')
def process_sync_replication(self): def process_sync_replication(self):
"""Process synchronous standby beahvior. """Process synchronous standby beahvior.
@@ -314,14 +432,17 @@ class Ha(object):
logger.warning("No standbys available!") logger.warning("No standbys available!")
logger.info("Assigning synchronous standby status to %s", picked) logger.info("Assigning synchronous standby status to %s", picked)
self.state_handler.set_synchronous_standby(picked) self.state_handler.config.set_synchronous_standby(picked)
if picked and picked != '*' and not allow_promote: if picked and picked != '*' and not allow_promote:
# Wait for PostgreSQL to enable synchronous mode and see if we can immediately set sync_standby # Wait for PostgreSQL to enable synchronous mode and see if we can immediately set sync_standby
time.sleep(2) time.sleep(2)
picked, allow_promote = self.state_handler.pick_synchronous_standby(self.cluster) picked, allow_promote = self.state_handler.pick_synchronous_standby(self.cluster)
if allow_promote: if allow_promote:
cluster = self.dcs.get_cluster() try:
cluster = self.dcs.get_cluster()
except DCSError:
return logger.warning("Could not get cluster state from DCS during process_sync_replication()")
if cluster.sync.leader and cluster.sync.leader != self.state_handler.name: if cluster.sync.leader and cluster.sync.leader != self.state_handler.name:
logger.info("Synchronous replication key updated by someone else") logger.info("Synchronous replication key updated by someone else")
return return
@@ -332,7 +453,7 @@ class Ha(object):
else: else:
if self.cluster.sync.leader and self.dcs.delete_sync_state(index=self.cluster.sync.index): if self.cluster.sync.leader and self.dcs.delete_sync_state(index=self.cluster.sync.index):
logger.info("Disabled synchronous replication") logger.info("Disabled synchronous replication")
self.state_handler.set_synchronous_standby(None) self.state_handler.config.set_synchronous_standby(None)
def is_sync_standby(self, cluster): def is_sync_standby(self, cluster):
return cluster.leader and cluster.sync.leader == cluster.leader.name \ return cluster.leader and cluster.sync.leader == cluster.leader.name \
@@ -393,6 +514,10 @@ class Ha(object):
line.append(cluster_history[line[0]][3]) line.append(cluster_history[line[0]][3])
self.dcs.set_history_value(json.dumps(history, separators=(',', ':'))) self.dcs.set_history_value(json.dumps(history, separators=(',', ':')))
def enforce_follow_remote_master(self, message):
demote_reason = 'cannot be a real master in standby cluster'
return self.follow(demote_reason, message)
def enforce_master_role(self, message, promote_message): def enforce_master_role(self, message, promote_message):
if not self.is_paused() and not self.watchdog.is_running and not self.watchdog.activate(): if not self.is_paused() and not self.watchdog.is_running and not self.watchdog.activate():
if self.state_handler.is_leader(): if self.state_handler.is_leader():
@@ -420,10 +545,17 @@ class Ha(object):
# Somebody else updated sync state, it may be due to us losing the lock. To be safe, postpone # Somebody else updated sync state, it may be due to us losing the lock. To be safe, postpone
# promotion until next cycle. TODO: trigger immediate retry of run_cycle # promotion until next cycle. TODO: trigger immediate retry of run_cycle
return 'Postponing promotion because synchronous replication state was updated by somebody else' return 'Postponing promotion because synchronous replication state was updated by somebody else'
self.state_handler.set_synchronous_standby('*' if self.is_synchronous_mode_strict() else None) self.state_handler.config.set_synchronous_standby('*' if self.is_synchronous_mode_strict() else None)
if self.state_handler.role != 'master': if self.state_handler.role != 'master':
self.set_leader_access_is_restricted(self.cluster.has_permanent_logical_slots(self.state_handler.name))
def on_success():
self._rewind.reset_state()
logger.info("cleared rewind state after becoming the leader")
self._async_executor.schedule('promote') self._async_executor.schedule('promote')
self._async_executor.run_async(self.state_handler.promote, args=(self.dcs.loop_wait,)) self._async_executor.run_async(self.state_handler.promote,
args=(self.dcs.loop_wait, on_success, self._leader_access_is_restricted))
return promote_message return promote_message
@staticmethod @staticmethod
@@ -437,7 +569,7 @@ class Ha(object):
logger.info('Got response from %s %s: %s', member.name, member.api_url, response.content) logger.info('Got response from %s %s: %s', member.name, member.api_url, response.content)
return _MemberStatus.from_api_response(member, response.json()) return _MemberStatus.from_api_response(member, response.json())
except Exception as e: except Exception as e:
logger.warning("request failed: GET %s (%s)", member.api_url, e) logger.warning("Request failed to %s: GET %s (%s)", member.name, member.api_url, e)
return _MemberStatus.unknown(member) return _MemberStatus.unknown(member)
def fetch_nodes_statuses(self, members): def fetch_nodes_statuses(self, members):
@@ -454,15 +586,23 @@ class Ha(object):
:returns True when node is lagging :returns True when node is lagging
""" """
lag = (self.cluster.last_leader_operation or 0) - wal_position lag = (self.cluster.last_leader_operation or 0) - wal_position
return lag > self.state_handler.config.get('maximum_lag_on_failover', 0) return lag > self.patroni.config.get('maximum_lag_on_failover', 0)
def _is_healthiest_node(self, members, check_replication_lag=True): def _is_healthiest_node(self, members, check_replication_lag=True):
"""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."""
_, 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')
return False # Too far behind last reported wal position on master return False # Too far behind last reported wal position on master
if not self.is_standby_cluster() and self.check_timeline():
cluster_timeline = self.cluster.timeline
my_timeline = self.state_handler.replica_cached_timeline(cluster_timeline)
if my_timeline < cluster_timeline:
logger.info('My timeline %s is behind last known cluster timeline %s', my_timeline, cluster_timeline)
return False
# Prepare list of nodes to run check against # Prepare list of nodes to run check against
members = [m for m in members if m.name != self.state_handler.name and not m.nofailover and m.api_url] members = [m for m in members if m.name != self.state_handler.name and not m.nofailover and m.api_url]
@@ -473,11 +613,17 @@ class Ha(object):
logger.warning('Master (%s) is still alive', st.member.name) logger.warning('Master (%s) is still alive', st.member.name)
return False return False
if my_wal_position < st.wal_position: if my_wal_position < st.wal_position:
return False logger.info('Wal position of %s is ahead of my wal position', st.member.name)
# In synchronous mode the former leader might be still accessible and even be ahead of us.
# We should not disqualify himself from the leader race in such a situation.
if not self.is_synchronous_mode() or st.member.name != self.cluster.sync.leader:
return False
logger.info('Ignoring the former leader being ahead of us')
return True return True
def is_failover_possible(self, members): def is_failover_possible(self, members):
ret = False ret = False
cluster_timeline = self.cluster.timeline
members = [m for m in members if m.name != self.state_handler.name and not m.nofailover and m.api_url] members = [m for m in members if m.name != self.state_handler.name and not m.nofailover and m.api_url]
if members: if members:
for st in self.fetch_nodes_statuses(members): for st in self.fetch_nodes_statuses(members):
@@ -486,6 +632,9 @@ class Ha(object):
logger.info('Member %s is %s', st.member.name, not_allowed_reason) logger.info('Member %s is %s', st.member.name, not_allowed_reason)
elif self.is_lagging(st.wal_position): elif self.is_lagging(st.wal_position):
logger.info('Member %s exceeds maximum replication lag', st.member.name) logger.info('Member %s exceeds maximum replication lag', st.member.name)
elif self.check_timeline() and (not st.timeline or st.timeline < cluster_timeline):
logger.info('Timeline %s of member %s is behind the cluster timeline %s',
st.timeline, st.member.name, cluster_timeline)
else: else:
ret = True ret = True
else: else:
@@ -577,10 +726,14 @@ class Ha(object):
return self._is_healthiest_node(members.values()) return self._is_healthiest_node(members.values())
def release_leader_key_voluntarily(self): def _delete_leader(self):
self.set_is_leader(False)
self.dcs.delete_leader() self.dcs.delete_leader()
self.touch_member()
self.dcs.reset_cluster() self.dcs.reset_cluster()
def release_leader_key_voluntarily(self):
self._delete_leader()
self.touch_member()
logger.info("Leader key released") logger.info("Leader key released")
def demote(self, mode): def demote(self, mode):
@@ -595,19 +748,21 @@ class Ha(object):
PostgreSQL as quickly as possible without regard for data durability. May only be called synchronously. PostgreSQL as quickly as possible without regard for data durability. May only be called synchronously.
""" """
mode_control = { mode_control = {
'offline': dict(stop='fast', checkpoint=False, release=False, offline=True, async=False), 'offline': dict(stop='fast', checkpoint=False, release=False, offline=True, async_req=False),
'graceful': dict(stop='fast', checkpoint=True, release=True, offline=False, async=False), 'graceful': dict(stop='fast', checkpoint=True, release=True, offline=False, async_req=False),
'immediate': dict(stop='immediate', checkpoint=False, release=True, offline=False, async=True), 'immediate': dict(stop='immediate', checkpoint=False, release=True, offline=False, async_req=True),
'immediate-nolock': dict(stop='immediate', checkpoint=False, release=False, offline=False, async=True), 'immediate-nolock': dict(stop='immediate', checkpoint=False, release=False, offline=False, async_req=True),
}[mode] }[mode]
self.state_handler.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)
self.state_handler.set_role('demoted') self.state_handler.set_role('demoted')
self.set_is_leader(False)
if mode_control['release']: if mode_control['release']:
self.release_leader_key_voluntarily() with self._async_executor:
self.release_leader_key_voluntarily()
time.sleep(2) # Give a time to somebody to take the leader lock time.sleep(2) # Give a time to somebody to take the leader lock
if mode_control['offline']: if mode_control['offline']:
node_to_follow, leader = None, None node_to_follow, leader = None, None
@@ -618,13 +773,13 @@ class Ha(object):
# FIXME: with mode offline called from DCS exception handler and handle_long_action_in_progress # FIXME: with mode offline called from DCS exception handler and handle_long_action_in_progress
# there could be an async action already running, calling follow from here will lead # there could be an async action already running, calling follow from here will lead
# to racy state handler state updates. # to racy state handler state updates.
if mode_control['async']: if mode_control['async_req']:
self._async_executor.schedule('starting after demotion') self._async_executor.schedule('starting after demotion')
self._async_executor.run_async(self.state_handler.follow, (node_to_follow,)) self._async_executor.run_async(self.state_handler.follow, (node_to_follow,))
else: else:
if self.is_synchronous_mode(): if self.is_synchronous_mode():
self.state_handler.set_synchronous_standby(None) self.state_handler.config.set_synchronous_standby(None)
if self.state_handler.rewind_needed_and_possible(leader): if self._rewind.rewind_or_reinitialize_needed_and_possible(leader):
return False # do not start postgres, but run pg_rewind on the next iteration return False # do not start postgres, but run pg_rewind on the next iteration
self.state_handler.follow(node_to_follow) self.state_handler.follow(node_to_follow)
@@ -721,8 +876,18 @@ class Ha(object):
logger.info('Cleaning up failover key after acquiring leader lock...') logger.info('Cleaning up failover key after acquiring leader lock...')
self.dcs.manual_failover('', '') self.dcs.manual_failover('', '')
self.load_cluster_from_dcs() self.load_cluster_from_dcs()
return self.enforce_master_role('acquired session lock as a leader',
'promoted self to leader by acquiring session lock') if self.is_standby_cluster():
# standby leader disappeared, and this is a healthiest
# replica, so it should become a new standby leader.
# This imply that we need to start following a remote master
msg = 'promoted self to a standby leader by acquiring session lock'
return self.enforce_follow_remote_master(msg)
else:
return self.enforce_master_role(
'acquired session lock as a leader',
'promoted self to leader by acquiring session lock'
)
else: else:
return self.follow('demoted self after trying and failing to obtain lock', return self.follow('demoted self after trying and failing to obtain lock',
'following new leader after trying and failing to obtain lock') 'following new leader after trying and failing to obtain lock')
@@ -730,7 +895,7 @@ class Ha(object):
# when we are doing manual failover there is no guaranty that new leader is ahead of any other node # when we are doing manual failover there is no guaranty that new leader is ahead of any other node
# node tagged as nofailover can be ahead of the new leader either, but it is always excluded from elections # node tagged as nofailover can be ahead of the new leader either, but it is always excluded from elections
if bool(self.cluster.failover) or self.patroni.nofailover: if bool(self.cluster.failover) or self.patroni.nofailover:
self.state_handler.trigger_check_diverged_lsn() self._rewind.trigger_check_diverged_lsn()
time.sleep(2) # Give a time to somebody to take the leader lock time.sleep(2) # Give a time to somebody to take the leader lock
if self.patroni.nofailover: if self.patroni.nofailover:
@@ -745,27 +910,50 @@ class Ha(object):
if self.cluster.failover and self.cluster.failover.candidate == self.state_handler.name: if self.cluster.failover and self.cluster.failover.candidate == self.state_handler.name:
return 'waiting to become master after promote...' return 'waiting to become master after promote...'
self.dcs.delete_leader() self._delete_leader()
self.dcs.reset_cluster()
return 'removed leader lock because postgres is not running as master' return 'removed leader lock because postgres is not running as master'
if self.state_handler.is_leader() and self._leader_access_is_restricted:
self.state_handler.slots_handler.sync_replication_slots(self.cluster)
self.state_handler.call_nowait(ACTION_ON_ROLE_CHANGE)
self.set_leader_access_is_restricted(False)
if self.update_lock(True): if self.update_lock(True):
msg = self.process_manual_failover_from_leader() msg = self.process_manual_failover_from_leader()
if msg is not None: if msg is not None:
return msg return msg
return self.enforce_master_role('no action. i am the leader with the lock', # check if the node is ready to be used by pg_rewind
'promoted self to leader because i had the session lock') self._rewind.check_for_checkpoint_after_promote()
if self.is_standby_cluster():
# in case of standby cluster we don't really need to
# enforce anything, since the leader is not a master.
# So just remind the role.
msg = 'no action. i am the standby leader with the lock' \
if self.state_handler.role == 'standby_leader' else \
'promoted self to a standby leader because i had the session lock'
return self.enforce_follow_remote_master(msg)
else:
return self.enforce_master_role(
'no action. i am the leader with the lock',
'promoted self to leader because i had the session lock'
)
else: else:
# Either there is no connection to DCS or someone else acquired the lock # Either there is no connection to DCS or someone else acquired the lock
logger.error('failed to update leader lock') logger.error('failed to update leader lock')
if self.state_handler.is_leader(): if self.state_handler.is_leader():
if self.is_paused():
return 'continue to run as master after failing to update leader lock in DCS'
self.demote('immediate-nolock') self.demote('immediate-nolock')
return 'demoted self because failed to update leader lock in DCS' return 'demoted self because failed to update leader lock in DCS'
else: else:
return 'not promoting because failed to update leader lock in DCS' return 'not promoting because failed to update leader lock in DCS'
else: else:
logger.info('does not have lock') logger.info('does not have lock')
if self.is_standby_cluster():
return self.follow('cannot be a real master in standby cluster',
'no action. i am a secondary and i am following a standby leader', refresh=False)
return self.follow('demoting self because i do not have the lock and i was a leader', return self.follow('demoting self because i do not have the lock and i was a leader',
'no action. i am a secondary and i am following a leader', refresh=False) 'no action. i am a secondary and i am following a leader', refresh=False)
@@ -802,8 +990,7 @@ class Ha(object):
if role and role != self.state_handler.role: if role and role != self.state_handler.role:
reason_to_cancel = "host role mismatch" reason_to_cancel = "host role mismatch"
if (postgres_version and if postgres_version and postgres_version_to_int(postgres_version) <= int(self.state_handler.server_version):
self.state_handler.postgres_version_to_int(postgres_version) <= int(self.state_handler.server_version)):
reason_to_cancel = "postgres version mismatch" reason_to_cancel = "postgres version mismatch"
if pending_restart and not self.state_handler.pending_restart: if pending_restart and not self.state_handler.pending_restart:
@@ -883,7 +1070,8 @@ class Ha(object):
def _do_reinitialize(self, cluster): def _do_reinitialize(self, cluster):
self.state_handler.stop('immediate') self.state_handler.stop('immediate')
self.state_handler.remove_data_directory() # Commented redundant data directory cleanup here
# self.state_handler.remove_data_directory()
clone_member = self.cluster.get_clone_member(self.state_handler.name) clone_member = self.cluster.get_clone_member(self.state_handler.name)
member_role = 'leader' if clone_member == self.cluster.leader else 'replica' member_role = 'leader' if clone_member == self.cluster.leader else 'replica'
@@ -896,7 +1084,7 @@ class Ha(object):
if self.cluster.is_unlocked(): if self.cluster.is_unlocked():
return 'Cluster has no leader, can not reinitialize' return 'Cluster has no leader, can not reinitialize'
if self.cluster.leader.name == self.state_handler.name: if self.has_lock(False):
return 'I am the leader, can not reinitialize' return 'I am the leader, can not reinitialize'
if force: if force:
@@ -942,8 +1130,7 @@ class Ha(object):
self.watchdog.disable() self.watchdog.disable()
if self.has_lock(): if self.has_lock():
self.state_handler.set_role('demoted') self.state_handler.set_role('demoted')
self.dcs.delete_leader() self._delete_leader()
self.dcs.reset_cluster()
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
@@ -967,7 +1154,7 @@ class Ha(object):
self.state_handler.set_role('master') self.state_handler.set_role('master')
self._async_executor.schedule('post_bootstrap') self._async_executor.schedule('post_bootstrap')
self._async_executor.run_async(self.state_handler.post_bootstrap, self._async_executor.run_async(self.state_handler.bootstrap.post_bootstrap,
args=(self.patroni.config['bootstrap'], self._post_bootstrap_task)) args=(self.patroni.config['bootstrap'], self._post_bootstrap_task))
return 'running post_bootstrap' return 'running post_bootstrap'
@@ -976,9 +1163,12 @@ class Ha(object):
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.state_handler.slots_handler.sync_replication_slots(self.cluster)
self.dcs.take_leader() self.dcs.take_leader()
self.set_is_leader(True)
self.state_handler.call_nowait(ACTION_ON_START) self.state_handler.call_nowait(ACTION_ON_START)
self.load_cluster_from_dcs() self.load_cluster_from_dcs()
return 'initialized a new cluster' return 'initialized a new cluster'
def handle_starting_instance(self): def handle_starting_instance(self):
@@ -1034,6 +1224,11 @@ class Ha(object):
if self.is_paused(): if self.is_paused():
self.watchdog.disable() self.watchdog.disable()
self._was_paused = True
else:
if self._was_paused:
self.state_handler.schedule_sanity_checks_after_pause()
self._was_paused = False
if not self.cluster.has_member(self.state_handler.name): if not self.cluster.has_member(self.state_handler.name):
self.touch_member() self.touch_member()
@@ -1057,7 +1252,7 @@ class Ha(object):
if self.state_handler.bootstrapping: if self.state_handler.bootstrapping:
return self.post_bootstrap() return self.post_bootstrap()
if self.recovering and not self.state_handler.need_rewind: if self.recovering and not self._rewind.is_needed:
self.recovering = False self.recovering = False
# Check if we tried to recover and failed # Check if we tried to recover and failed
msg = self.post_recover() msg = self.post_recover()
@@ -1079,9 +1274,20 @@ class Ha(object):
return self.bootstrap() # new node return self.bootstrap() # new node
# "bootstrap", but data directory is not empty # "bootstrap", but data directory is not empty
elif not self.sysid_valid(self.cluster.initialize) and self.cluster.is_unlocked() and not self.is_paused(): elif not self.sysid_valid(self.cluster.initialize) and self.cluster.is_unlocked() and not self.is_paused():
if not self.state_handler.cb_called and self.state_handler.is_running() \
and not self.state_handler.is_leader():
self._join_aborted = True
logger.error('No initialize key in DCS and PostgreSQL is running as replica, aborting start')
logger.error('Please first start Patroni on the node running as master')
sys.exit(1)
self.dcs.initialize(create_new=(self.cluster.initialize is None), sysid=self.state_handler.sysid) self.dcs.initialize(create_new=(self.cluster.initialize is None), sysid=self.state_handler.sysid)
else: else:
# check if we are allowed to join # check if we are allowed to join
data_sysid = self.state_handler.sysid
if not self.sysid_valid(data_sysid):
# 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"
if self.sysid_valid(self.cluster.initialize) and self.cluster.initialize != self.state_handler.sysid: if self.sysid_valid(self.cluster.initialize) and self.cluster.initialize != self.state_handler.sysid:
logger.fatal("system ID mismatch, node %s belongs to a different cluster: %s != %s", logger.fatal("system ID mismatch, node %s belongs to a different cluster: %s != %s",
self.state_handler.name, self.cluster.initialize, self.state_handler.sysid) self.state_handler.name, self.cluster.initialize, self.state_handler.sysid)
@@ -1090,11 +1296,15 @@ class Ha(object):
if not self.state_handler.is_healthy(): if not self.state_handler.is_healthy():
if self.is_paused(): if self.is_paused():
if self.has_lock(): if self.has_lock():
self.dcs.delete_leader() self._delete_leader()
self.dcs.reset_cluster()
return 'removed leader lock because postgres is not running' return 'removed leader lock because postgres is not running'
elif not (self.state_handler.rewind_executed or # Normally we don't start Postgres in a paused state. We make an exception for the demoted primary
self.state_handler.need_rewind and self.state_handler.can_rewind): # that needs to be started after it had been stopped by demote. When there is no need to call rewind
# the demote code follows through to starting Postgres right away, however, in the rewind case
# it returns from demote and reaches this point to start PostgreSQL again after rewind. In that
# case it makes no sense to continue to recover() unless rewind has finished successfully.
elif self._rewind.failed or not self._rewind.executed and not \
(self._rewind.is_needed and self._rewind.can_rewind_or_reinitialize_allowed):
return 'postgres is not running' return 'postgres is not running'
# try to start dead postgres # try to start dead postgres
@@ -1111,11 +1321,11 @@ class Ha(object):
# stops PostgreSQL, therefore, we only reload replication slots if no # stops PostgreSQL, therefore, we only reload replication slots if no
# asynchronous processes are running (should be always the case for the master) # asynchronous processes are running (should be always the case for the master)
if not self._async_executor.busy and not self.state_handler.is_starting(): if not self._async_executor.busy and not self.state_handler.is_starting():
self.state_handler.slots_handler.sync_replication_slots(self.cluster)
if not self.state_handler.cb_called: if not self.state_handler.cb_called:
if not self.state_handler.is_leader(): if not self.state_handler.is_leader():
self.state_handler.trigger_check_diverged_lsn() self._rewind.trigger_check_diverged_lsn()
self.state_handler.call_nowait(ACTION_ON_START) self.state_handler.call_nowait(ACTION_ON_START)
self.state_handler.sync_replication_slots(self.cluster)
except DCSError: except DCSError:
dcs_failed = True dcs_failed = True
logger.error('Error communicating with DCS') logger.error('Error communicating with DCS')
@@ -1138,7 +1348,7 @@ class Ha(object):
if self.is_paused(): if self.is_paused():
logger.info('Leader key is not deleted and Postgresql is not stopped due paused state') logger.info('Leader key is not deleted and Postgresql is not stopped due paused state')
self.watchdog.disable() self.watchdog.disable()
else: elif not self._join_aborted:
# FIXME: If stop doesn't reach safepoint quickly enough keepalive is triggered. If shutdown checkpoint # FIXME: If stop doesn't reach safepoint quickly enough keepalive is triggered. If shutdown checkpoint
# takes longer than ttl, then leader key is lost and replication might not have sent out all xlog. # takes longer than ttl, then leader key is lost and replication might not have sent out all xlog.
# 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.
@@ -1148,6 +1358,7 @@ class Ha(object):
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()
self.touch_member()
else: else:
# XXX: what about when Patroni is started as the wrong user that has access to the watchdog device # XXX: what about when Patroni is started as the wrong user that has access to the watchdog device
# but cannot shut down PostgreSQL. Root would be the obvious example. Would be nice to not kill the # but cannot shut down PostgreSQL. Root would be the obvious example. Would be nice to not kill the
@@ -1156,13 +1367,11 @@ class Ha(object):
(" Leaving watchdog running." if self.watchdog.is_running else "")) (" Leaving watchdog running." if self.watchdog.is_running else ""))
def watch(self, timeout): def watch(self, timeout):
cluster = self.cluster
# watch on leader key changes if the postgres is running and leader is known and current node is not lock owner # watch on leader key changes if the postgres is running and leader is known and current node is not lock owner
if not self._async_executor.busy and cluster and cluster.leader \ if self._async_executor.busy or self.cluster.is_unlocked() or self.has_lock(False):
and cluster.leader.name != self.state_handler.name:
leader_index = cluster.leader.index
else:
leader_index = None leader_index = None
else:
leader_index = self.cluster.leader.index
return self.dcs.watch(leader_index, timeout) return self.dcs.watch(leader_index, timeout)
@@ -1171,3 +1380,25 @@ class Ha(object):
no "active" leader watch request in progress. no "active" leader watch request in progress.
This usually happens on the master or if the node is running async action""" This usually happens on the master or if the node is running async action"""
self.dcs.event.set() self.dcs.event.set()
def get_remote_member(self, member=None):
""" In case of standby cluster this will tel us from which remote
master to stream. Config can be both patroni config or
cluster.config.data
"""
cluster_params = self.get_standby_cluster_config()
if cluster_params:
name = member.name if member else 'remote_master:{}'.format(uuid.uuid1())
data = {k: v for k, v in cluster_params.items() if k in RemoteMember.allowed_keys()}
data['no_replication_slot'] = 'primary_slot_name' not in cluster_params
conn_kwargs = member.conn_kwargs() if member else \
{k: cluster_params[k] for k in ('host', 'port') if k in cluster_params}
if conn_kwargs:
data['conn_kwargs'] = conn_kwargs
return RemoteMember(name, data)
def get_remote_master(self):
return self.get_remote_member()
+158
View File
@@ -0,0 +1,158 @@
import logging
import os
import sys
from copy import deepcopy
from logging.handlers import RotatingFileHandler
from patroni.utils import deep_compare
from six.moves.queue import Queue, Full
from threading import Lock, Thread
_LOGGER = logging.getLogger(__name__)
class QueueHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.queue = Queue()
self._records_lost = 0
def _put_record(self, record):
self.format(record)
record.msg = record.message
record.args = None
record.exc_info = None
self.queue.put_nowait(record)
def _try_to_report_lost_records(self):
if self._records_lost:
try:
record = _LOGGER.makeRecord(_LOGGER.name, logging.WARNING, __file__, 0,
'QueueHandler has lost %s log records',
(self._records_lost,), None, 'emit')
self._put_record(record)
self._records_lost = 0
except Exception:
pass
def emit(self, record):
try:
self._put_record(record)
self._try_to_report_lost_records()
except Exception:
self._records_lost += 1
@property
def records_lost(self):
return self._records_lost
class PatroniLogger(Thread):
DEFAULT_LEVEL = 'INFO'
DEFAULT_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
NORMAL_LOG_QUEUE_SIZE = 2 # When everything goes normal Patroni writes only 2 messages per HA loop
DEFAULT_MAX_QUEUE_SIZE = 1000
LOGGING_BROKEN_EXIT_CODE = 5
def __init__(self):
super(PatroniLogger, self).__init__()
self.daemon = True
self._queue_handler = QueueHandler()
self._root_logger = logging.getLogger()
self._root_logger.addHandler(self._queue_handler)
self._config = None
self._log_handler = None
self._old_handlers = []
self._log_handler_lock = Lock()
self.reload_config({'level': 'DEBUG'})
self.start()
def update_loggers(self):
loggers = deepcopy(self._config.get('loggers') or {})
for name, logger in self._root_logger.manager.loggerDict.items():
if not isinstance(logger, logging.PlaceHolder):
level = loggers.pop(name, logging.NOTSET)
logger.setLevel(level)
for name, level in loggers.items():
logger = self._root_logger.manager.getLogger(name)
logger.setLevel(level)
def reload_config(self, config):
if self._config is None or not deep_compare(self._config, config):
with self._queue_handler.queue.mutex:
self._queue_handler.queue.maxsize = config.get('max_queue_size', self.DEFAULT_MAX_QUEUE_SIZE)
self._root_logger.setLevel(config.get('level', PatroniLogger.DEFAULT_LEVEL))
new_handler = None
if 'dir' in config:
if not isinstance(self._log_handler, RotatingFileHandler):
new_handler = RotatingFileHandler(os.path.join(config['dir'], __name__))
handler = new_handler or self._log_handler
handler.maxBytes = int(config.get('file_size', 25000000))
handler.backupCount = int(config.get('file_num', 4))
else:
if self._log_handler is None or isinstance(self._log_handler, RotatingFileHandler):
new_handler = logging.StreamHandler()
handler = new_handler or self._log_handler
oldlogformat = (self._config or {}).get('format', PatroniLogger.DEFAULT_FORMAT)
logformat = config.get('format', PatroniLogger.DEFAULT_FORMAT)
olddateformat = (self._config or {}).get('dateformat') or None
dateformat = config.get('dateformat') or None # Convert empty string to `None`
if oldlogformat != logformat or olddateformat != dateformat or new_handler:
handler.setFormatter(logging.Formatter(logformat, dateformat))
if new_handler:
with self._log_handler_lock:
if self._log_handler:
self._old_handlers.append(self._log_handler)
self._log_handler = new_handler
self._config = config.copy()
self.update_loggers()
def _close_old_handlers(self):
while True:
with self._log_handler_lock:
if not self._old_handlers:
break
handler = self._old_handlers.pop()
try:
handler.close()
except Exception:
_LOGGER.exception('Failed to close the old log handler %s', handler)
def run(self):
while True:
self._close_old_handlers()
record = self._queue_handler.queue.get(True)
if record is None:
break
self._log_handler.handle(record)
self._queue_handler.queue.task_done()
def shutdown(self):
try:
self._queue_handler.queue.put_nowait(None)
except Full: # Queue is full.
# It seems that logging is not working, exiting with non-standard exit-code is the best we can do.
sys.exit(self.LOGGING_BROKEN_EXIT_CODE)
self.join()
logging.shutdown()
@property
def queue_size(self):
return self._queue_handler.queue.qsize()
@property
def records_lost(self):
return self._queue_handler.records_lost
File diff suppressed because it is too large Load Diff
+902
View File
@@ -0,0 +1,902 @@
import logging
import os
import psycopg2
import shlex
import shutil
import subprocess
import time
from contextlib import contextmanager
from copy import deepcopy
from patroni.postgresql.callback_executor import CallbackExecutor
from patroni.postgresql.bootstrap import Bootstrap
from patroni.postgresql.cancellable import CancellableSubprocess
from patroni.postgresql.config import ConfigHandler
from patroni.postgresql.connection import Connection, get_connection_cursor
from patroni.postgresql.misc import parse_history, postgres_major_version_to_int
from patroni.postgresql.postmaster import PostmasterProcess
from patroni.postgresql.slots import SlotsHandler
from patroni.exceptions import PostgresConnectionException
from patroni.utils import Retry, RetryFailedError, polling_loop
from patroni.dcs import slot_name_from_member_name, RemoteMember
from threading import current_thread, Lock
logger = logging.getLogger(__name__)
ACTION_ON_START = "on_start"
ACTION_ON_STOP = "on_stop"
ACTION_ON_RESTART = "on_restart"
ACTION_ON_RELOAD = "on_reload"
ACTION_ON_ROLE_CHANGE = "on_role_change"
ACTION_NOOP = "noop"
STATE_RUNNING = 'running'
STATE_REJECT = 'rejecting connections'
STATE_NO_RESPONSE = 'not responding'
STATE_UNKNOWN = 'unknown'
STOP_POLLING_INTERVAL = 1
cluster_info_query = ("SELECT CASE WHEN pg_catalog.pg_is_in_recovery() THEN 0 "
"ELSE ('x' || pg_catalog.substr(pg_catalog.pg_{0}file_name("
"pg_catalog.pg_current_{0}_{1}()), 1, 8))::bit(32)::int END, "
"CASE WHEN pg_catalog.pg_is_in_recovery() THEN GREATEST("
" pg_catalog.pg_{0}_{1}_diff(COALESCE("
"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)"
"ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), '0/0')::bigint END")
@contextmanager
def null_context():
yield
class Postgresql(object):
def __init__(self, config):
self.name = config['name']
self.scope = config['scope']
self._data_dir = config['data_dir']
self._database = config.get('database', 'postgres')
self._version_file = os.path.join(self._data_dir, 'PG_VERSION')
self._major_version = self.get_major_version()
self._state_lock = Lock()
self.set_state('stopped')
self._pending_restart = False
self._connection = Connection()
self.config = ConfigHandler(self, config)
self._bin_dir = config.get('bin_dir') or ''
self.bootstrap = Bootstrap(self)
self.bootstrapping = False
self.__thread_ident = current_thread().ident
self.slots_handler = SlotsHandler(self)
self._pgpass = config.get('pgpass') or os.path.join(os.path.expanduser('~'), 'pgpass')
self._callback_executor = CallbackExecutor()
self.__cb_called = False
self.__cb_pending = None
self.cancellable = CancellableSubprocess()
self._sysid = None
self.retry = Retry(max_tries=-1, deadline=config['retry_timeout']/2.0, max_delay=1,
retry_exceptions=PostgresConnectionException)
# Retry 'pg_is_in_recovery()' only once
self._is_leader_retry = Retry(max_tries=1, deadline=config['retry_timeout']/2.0, max_delay=1,
retry_exceptions=PostgresConnectionException)
self._role_lock = Lock()
self.set_role(self.get_postgres_role_from_data_directory())
self._state_entry_timestamp = None
self._cluster_info_state = {}
self._cached_replica_timeline = None
# Last known running process
self._postmaster_proc = None
if self.is_running():
self.set_state('running')
self.set_role('master' if self.is_leader() else 'replica')
self.config.write_postgresql_conf() # we are "joining" already running postgres
hba_saved = self.config.replace_pg_hba()
ident_saved = self.config.replace_pg_ident()
if hba_saved or ident_saved:
self.reload()
elif self.role == 'master':
self.set_role('demoted')
@property
def create_replica_methods(self):
return self.config.get('create_replica_methods', []) or self.config.get('create_replica_method', [])
@property
def major_version(self):
return self._major_version
@property
def database(self):
return self._database
@property
def data_dir(self):
return self._data_dir
@property
def callback(self):
return self.config.get('callbacks') or {}
@property
def wal_name(self):
return 'wal' if self._major_version >= 100000 else 'xlog'
@property
def lsn_name(self):
return 'lsn' if self._major_version >= 100000 else 'location'
def _version_file_exists(self):
return not self.data_directory_empty() and os.path.isfile(self._version_file)
def get_major_version(self):
if self._version_file_exists():
try:
with open(self._version_file) as f:
return postgres_major_version_to_int(f.read().strip())
except Exception:
logger.exception('Failed to read PG_VERSION from %s', self._data_dir)
return 0
def pgcommand(self, cmd):
"""Returns path to the specified PostgreSQL command"""
return os.path.join(self._bin_dir, cmd)
def pg_ctl(self, cmd, *args, **kwargs):
"""Builds and executes pg_ctl command
:returns: `!True` when return_code == 0, otherwise `!False`"""
pg_ctl = [self.pgcommand('pg_ctl'), cmd]
return subprocess.call(pg_ctl + ['-D', self._data_dir] + list(args), **kwargs) == 0
def pg_isready(self):
"""Runs pg_isready to see if PostgreSQL is accepting connections.
:returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up."""
r = self.config.local_connect_kwargs
cmd = [self.pgcommand('pg_isready'), '-p', r['port'], '-d', self._database]
# Host is not set if we are connecting via default unix socket
if 'host' in r:
cmd.extend(['-h', r['host']])
# We only need the username because pg_isready does not try to authenticate
if 'user' in r:
cmd.extend(['-U', r['user']])
ret = subprocess.call(cmd)
return_codes = {0: STATE_RUNNING,
1: STATE_REJECT,
2: STATE_NO_RESPONSE,
3: STATE_UNKNOWN}
return return_codes.get(ret, STATE_UNKNOWN)
def reload_config(self, config):
self.config.reload_config(config)
self._is_leader_retry.deadline = self.retry.deadline = config['retry_timeout']/2.0
@property
def pending_restart(self):
return self._pending_restart
def set_pending_restart(self, value):
self._pending_restart = value
@property
def sysid(self):
if not self._sysid and not self.bootstrapping:
data = self.controldata()
self._sysid = data.get('Database system identifier', "")
return self._sysid
def get_postgres_role_from_data_directory(self):
if self.data_directory_empty():
return 'uninitialized'
elif self.config.recovery_conf_exists():
return 'replica'
else:
return 'master'
@property
def server_version(self):
return self._connection.server_version
def connection(self):
return self._connection.get()
def set_connection_kwargs(self, kwargs):
self._connection.set_conn_kwargs(kwargs)
def _query(self, sql, *params):
"""We are always using the same cursor, therefore this method is not thread-safe!!!
You can call it from different threads only if you are holding explicit `AsyncExecutor` lock,
because the main thread is always holding this lock when running HA cycle."""
cursor = None
try:
cursor = self._connection.cursor()
cursor.execute(sql, params)
return cursor
except psycopg2.Error as e:
if cursor and cursor.connection.closed == 0:
# When connected via unix socket, psycopg2 can't recoginze 'connection lost'
# and leaves `_cursor_holder.connection.closed == 0`, but psycopg2.OperationalError
# is still raised (what is correct). It doesn't make sense to continiue with existing
# connection and we will close it, to avoid its reuse by the `cursor` method.
if isinstance(e, psycopg2.OperationalError):
self._connection.close()
else:
raise e
if self.state == 'restarting':
raise RetryFailedError('cluster is being restarted')
raise PostgresConnectionException('connection problems')
def query(self, sql, *args, **kwargs):
if not kwargs.get('retry', True):
return self._query(sql, *args)
try:
return self.retry(self._query, sql, *args)
except RetryFailedError as e:
raise PostgresConnectionException(str(e))
def data_directory_empty(self):
return not os.path.exists(self._data_dir) or os.listdir(self._data_dir) == []
def write_pgpass(self, record):
if 'user' not in record or 'password' not in record:
return os.environ.copy()
with open(self._pgpass, 'w') as f:
if os.name != 'nt':
os.fchmod(f.fileno(), 0o600)
f.write('{host}:{port}:*:{user}:{password}\n'.format(**record))
env = os.environ.copy()
env['PGPASSFILE'] = self._pgpass
return env
def replica_method_options(self, method):
return deepcopy(self.config.get(method, {}))
def replica_method_can_work_without_replication_connection(self, method):
return method != 'basebackup' and self.replica_method_options(method).get('no_master')
def can_create_replica_without_replication_connection(self, replica_methods=None):
""" go through the replication methods to see if there are ones
that does not require a working replication connection.
"""
if replica_methods is None:
replica_methods = self.create_replica_methods
return any(self.replica_method_can_work_without_replication_connection(m) for m in replica_methods)
def reset_cluster_info_state(self):
self._cluster_info_state = {}
def _cluster_info_state_get(self, name):
if not self._cluster_info_state:
stmt = cluster_info_query.format(self.wal_name, self.lsn_name)
try:
result = self._is_leader_retry(self._query, stmt).fetchone()
self._cluster_info_state = dict(zip(['timeline', 'wal_position'], result))
except RetryFailedError as e: # SELECT failed two times
self._cluster_info_state = {'error': str(e)}
if not self.is_starting() and self.pg_isready() == STATE_REJECT:
self.set_state('starting')
if 'error' in self._cluster_info_state:
raise PostgresConnectionException(self._cluster_info_state['error'])
return self._cluster_info_state.get(name)
def is_leader(self):
return bool(self._cluster_info_state_get('timeline'))
def is_running(self):
"""Returns PostmasterProcess if one is running on the data directory or None. If most recently seen process
is running updates the cached process based on pid file."""
if self._postmaster_proc:
if self._postmaster_proc.is_running():
return self._postmaster_proc
self._postmaster_proc = None
# we noticed that postgres was restarted, force syncing of replication
self.slots_handler.schedule()
self._postmaster_proc = PostmasterProcess.from_pidfile(self._data_dir)
return self._postmaster_proc
@property
def cb_called(self):
return self.__cb_called
def call_nowait(self, cb_name):
""" pick a callback command and call it without waiting for it to finish """
if self.bootstrapping:
return
if cb_name in (ACTION_ON_START, ACTION_ON_STOP, ACTION_ON_RESTART, ACTION_ON_ROLE_CHANGE):
self.__cb_called = True
if self.callback and cb_name in self.callback:
cmd = self.callback[cb_name]
try:
cmd = shlex.split(self.callback[cb_name]) + [cb_name, self.role, self.scope]
self._callback_executor.call(cmd)
except Exception:
logger.exception('callback %s %s %s %s failed', cmd, cb_name, self.role, self.scope)
@property
def role(self):
with self._role_lock:
return self._role
def set_role(self, value):
with self._role_lock:
self._role = value
@property
def state(self):
with self._state_lock:
return self._state
def set_state(self, value):
with self._state_lock:
self._state = value
self._state_entry_timestamp = time.time()
def time_in_state(self):
return time.time() - self._state_entry_timestamp
def is_starting(self):
return self.state == 'starting'
def wait_for_port_open(self, postmaster, timeout):
"""Waits until PostgreSQL opens ports."""
for _ in polling_loop(timeout):
if self.cancellable.is_cancelled:
return False
if not postmaster.is_running():
logger.error('postmaster is not running')
self.set_state('start failed')
return False
isready = self.pg_isready()
if isready != STATE_NO_RESPONSE:
if isready not in [STATE_REJECT, STATE_RUNNING]:
logger.warning("Can't determine PostgreSQL startup status, assuming running")
return True
logger.warning("Timed out waiting for PostgreSQL to start")
return False
def start(self, timeout=None, task=None, block_callbacks=False, role=None):
"""Start PostgreSQL
Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion
or failure.
:returns: True if start was initiated and postmaster ports are open, False if start failed"""
# make sure we close all connections established against
# the former node, otherwise, we might get a stalled one
# after kill -9, which would report incorrect data to
# patroni.
self._connection.close()
if self.is_running():
logger.error('Cannot start PostgreSQL because one is already running.')
self.set_state('starting')
return True
if not block_callbacks:
self.__cb_pending = ACTION_ON_START
self.set_role(role or self.get_postgres_role_from_data_directory())
self.set_state('starting')
self._pending_restart = False
configuration = self.config.effective_configuration
self.config.write_postgresql_conf(configuration)
self.config.resolve_connection_addresses()
self.config.replace_pg_hba()
self.config.replace_pg_ident()
options = ['--{0}={1}'.format(p, configuration[p]) for p in self.config.CMDLINE_OPTIONS
if p in configuration and p != 'wal_keep_segments']
if self.cancellable.is_cancelled:
return False
with task or null_context():
if task and task.is_cancelled:
logger.info("PostgreSQL start cancelled.")
return False
self._postmaster_proc = PostmasterProcess.start(self.pgcommand('postgres'),
self._data_dir,
self.config.postgresql_conf,
options)
if task:
task.complete(self._postmaster_proc)
start_timeout = timeout
if not start_timeout:
try:
start_timeout = float(self.config.get('pg_ctl_timeout', 60))
except ValueError:
start_timeout = 60
# We want postmaster to open ports before we continue
if not self._postmaster_proc or not self.wait_for_port_open(self._postmaster_proc, start_timeout):
return False
ret = self.wait_for_startup(start_timeout)
if ret is not None:
return ret
elif timeout is not None:
return False
else:
return None
def checkpoint(self, connect_kwargs=None):
check_not_is_in_recovery = connect_kwargs is not None
connect_kwargs = connect_kwargs or self.config.local_connect_kwargs
for p in ['connect_timeout', 'options']:
connect_kwargs.pop(p, None)
try:
with get_connection_cursor(**connect_kwargs) as cur:
cur.execute("SET statement_timeout = 0")
if check_not_is_in_recovery:
cur.execute('SELECT pg_catalog.pg_is_in_recovery()')
if cur.fetchone()[0]:
return 'is_in_recovery=true'
return cur.execute('CHECKPOINT')
except psycopg2.Error:
logger.exception('Exception during CHECKPOINT')
return 'not accessible or not healty'
def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None):
"""Stop PostgreSQL
Supports a callback when a safepoint is reached. A safepoint is when no user backend can return a successful
commit to users. Currently this means we wait for user backends to close. But in the future alternate mechanisms
could be added.
:param on_safepoint: This callback is called when no user backends are running.
"""
if checkpoint is None:
checkpoint = False if mode == 'immediate' else True
success, pg_signaled = self._do_stop(mode, block_callbacks, checkpoint, on_safepoint)
if success:
# block_callbacks is used during restart to avoid
# running start/stop callbacks in addition to restart ones
if not block_callbacks:
self.set_state('stopped')
if pg_signaled:
self.call_nowait(ACTION_ON_STOP)
else:
logger.warning('pg_ctl stop failed')
self.set_state('stop failed')
return success
def _do_stop(self, mode, block_callbacks, checkpoint, on_safepoint):
postmaster = self.is_running()
if not postmaster:
if on_safepoint:
on_safepoint()
return True, False
if checkpoint and not self.is_starting():
self.checkpoint()
if not block_callbacks:
self.set_state('stopping')
# Send signal to postmaster to stop
success = postmaster.signal_stop(mode)
if success is not None:
if success and on_safepoint:
on_safepoint()
return success, True
# We can skip safepoint detection if we don't have a callback
if on_safepoint:
# Wait for our connection to terminate so we can be sure that no new connections are being initiated
self._wait_for_connection_close(postmaster)
postmaster.wait_for_user_backends_to_close()
on_safepoint()
postmaster.wait()
return True, True
@staticmethod
def terminate_starting_postmaster(postmaster):
"""Terminates a postmaster that has not yet opened ports or possibly even written a pid file. Blocks
until the process goes away."""
postmaster.signal_stop('immediate')
postmaster.wait()
def _wait_for_connection_close(self, postmaster):
try:
with self.connection().cursor() as cur:
while postmaster.is_running(): # Need a timeout here?
cur.execute("SELECT 1")
time.sleep(STOP_POLLING_INTERVAL)
except psycopg2.Error:
pass
def reload(self):
ret = self.pg_ctl('reload')
if ret:
self.call_nowait(ACTION_ON_RELOAD)
return ret
def check_for_startup(self):
"""Checks PostgreSQL status and returns if PostgreSQL is in the middle of startup."""
return self.is_starting() and not self.check_startup_state_changed()
def check_startup_state_changed(self):
"""Checks if PostgreSQL has completed starting up or failed or still starting.
Should only be called when state == 'starting'
:returns: True if state was changed from 'starting'
"""
ready = self.pg_isready()
if ready == STATE_REJECT:
return False
elif ready == STATE_NO_RESPONSE:
self.set_state('start failed')
self.slots_handler.schedule(False) # TODO: can remove this?
self.config.save_configuration_files(True) # TODO: maybe remove this?
return True
else:
if ready != STATE_RUNNING:
# Bad configuration or unexpected OS error. No idea of PostgreSQL status.
# Let the main loop of run cycle clean up the mess.
logger.warning("%s status returned from pg_isready",
"Unknown" if ready == STATE_UNKNOWN else "Invalid")
self.set_state('running')
self.slots_handler.schedule()
self.config.save_configuration_files(True)
# TODO: __cb_pending can be None here after PostgreSQL restarts on its own. Do we want to call the callback?
# Previously we didn't even notice.
action = self.__cb_pending or ACTION_ON_START
self.call_nowait(action)
self.__cb_pending = None
return True
def wait_for_startup(self, timeout=None):
"""Waits for PostgreSQL startup to complete or fail.
:returns: True if start was successful, False otherwise"""
if not self.is_starting():
# Should not happen
logger.warning("wait_for_startup() called when not in starting state")
while not self.check_startup_state_changed():
if self.cancellable.is_cancelled or timeout and self.time_in_state() > timeout:
return None
time.sleep(1)
return self.state == 'running'
def restart(self, timeout=None, task=None, block_callbacks=False, role=None):
"""Restarts PostgreSQL.
When timeout parameter is set the call will block either until PostgreSQL has started, failed to start or
timeout arrives.
:returns: True when restart was successful and timeout did not expire when waiting.
"""
self.set_state('restarting')
if not block_callbacks:
self.__cb_pending = ACTION_ON_RESTART
ret = self.stop(block_callbacks=True) and self.start(timeout, task, True, role)
if not ret and not self.is_starting():
self.set_state('restart failed ({0})'.format(self.state))
return ret
def is_healthy(self):
if not self.is_running():
logger.warning('Postgresql is not running.')
return False
return True
def controldata(self):
""" return the contents of pg_controldata, or non-True value if pg_controldata call failed """
result = {}
# Don't try to call pg_controldata during backup restore
if self._version_file_exists() and self.state != 'creating replica':
try:
env = {'LANG': 'C', 'LC_ALL': 'C', 'PATH': os.getenv('PATH')}
if os.getenv('SYSTEMROOT') is not None:
env['SYSTEMROOT'] = os.getenv('SYSTEMROOT')
data = subprocess.check_output([self.pgcommand('pg_controldata'), self._data_dir], env=env)
if data:
data = data.decode('utf-8').splitlines()
# pg_controldata output depends on major verion. Some of parameters are prefixed by 'Current '
result = {l.split(':')[0].replace('Current ', '', 1): l.split(':', 1)[1].strip() for l in data
if l and ':' in l}
except subprocess.CalledProcessError:
logger.exception("Error when calling pg_controldata")
return result
@contextmanager
def get_replication_connection_cursor(self, host='localhost', port=5432, database=None, **kwargs):
replication = self.config.replication
with get_connection_cursor(host=host, port=int(port), database=database or self._database, replication=1,
user=replication['username'], password=replication.get('password'),
connect_timeout=3, options='-c statement_timeout=2000') as cur:
yield cur
def get_local_timeline_lsn_from_replication_connection(self):
timeline = lsn = None
try:
with self.get_replication_connection_cursor(**self.config.local_replication_address) as cur:
cur.execute('IDENTIFY_SYSTEM')
timeline, lsn = cur.fetchone()[1:3]
except Exception:
logger.exception('Can not fetch local timeline and lsn from replication connection')
return timeline, lsn
def get_replica_timeline(self):
return self.get_local_timeline_lsn_from_replication_connection()[0]
def replica_cached_timeline(self, master_timeline):
if not self._cached_replica_timeline or not master_timeline or self._cached_replica_timeline != master_timeline:
self._cached_replica_timeline = self.get_replica_timeline()
return self._cached_replica_timeline
def get_master_timeline(self):
return self._cluster_info_state_get('timeline')
def get_history(self, timeline):
history_path = 'pg_{0}/{1:08X}.history'.format(self.wal_name, timeline)
try:
cursor = self._connection.cursor()
cursor.execute('SELECT isdir, modification FROM pg_catalog.pg_stat_file(%s)', (history_path,))
isdir, modification = cursor.fetchone()
if not isdir:
cursor.execute('SELECT pg_catalog.pg_read_file(%s)', (history_path,))
history = list(parse_history(cursor.fetchone()[0]))
if history[-1][0] == timeline - 1:
history[-1].append(modification.isoformat())
return history
except Exception:
logger.exception('Failed to read and parse %s', (history_path,))
def follow(self, member, role='replica', timeout=None):
is_remote_master = isinstance(member, RemoteMember)
no_replication_slot = is_remote_master and member.no_replication_slot
restore_command = is_remote_master and member.restore_command
min_apply_delay = is_remote_master and member.recovery_min_apply_delay
archive_cleanup = is_remote_master and member.archive_cleanup_command
primary_conninfo = self.config.primary_conninfo(member)
change_role = self.cb_called and (self.role in ('master', 'demoted') or
not {'standby_leader', 'replica'} - {self.role, role})
recovery_params = self.config.get('recovery_conf', {}).copy()
recovery_params.update({'standby_mode': 'on', 'recovery_target_timeline': 'latest'})
if primary_conninfo:
recovery_params['primary_conninfo'] = primary_conninfo
if self.slots_handler.use_slots and not no_replication_slot:
required_name = is_remote_master and member.data.get('primary_slot_name')
name = required_name or slot_name_from_member_name(self.name)
recovery_params['primary_slot_name'] = name
if restore_command:
recovery_params['restore_command'] = restore_command
if min_apply_delay:
recovery_params['recovery_min_apply_delay'] = min_apply_delay
if archive_cleanup:
recovery_params['archive_cleanup_command'] = archive_cleanup
self.config.write_recovery_conf(recovery_params)
# When we demoting the master or standby_leader to replica or promoting replica to a standby_leader
# and we know for sure that postgres was already running before, we will only execute on_role_change
# callback and prevent execution of on_restart/on_start callback.
# If the role remains the same (replica or standby_leader), we will execute on_start or on_restart
if change_role:
self.__cb_pending = ACTION_NOOP
if self.is_running():
self.restart(block_callbacks=change_role, role=role)
else:
self.start(timeout=timeout, block_callbacks=change_role, role=role)
if change_role:
# TODO: postpone this until start completes, or maybe do even earlier
self.call_nowait(ACTION_ON_ROLE_CHANGE)
return True
def _wait_promote(self, wait_seconds):
for _ in polling_loop(wait_seconds):
data = self.controldata()
if data.get('Database cluster state') == 'in production':
return True
def promote(self, wait_seconds, on_success=None, access_is_restricted=False):
if self.role == 'master':
return True
ret = self.pg_ctl('promote', '-W')
if ret:
self.set_role('master')
if on_success is not None:
on_success()
if not access_is_restricted:
self.call_nowait(ACTION_ON_ROLE_CHANGE)
ret = self._wait_promote(wait_seconds)
return ret
def timeline_wal_position(self):
# This method could be called from different threads (simultaneously with some other `_query` calls).
# If it is called not from main thread we will create a new cursor to execute statement.
if current_thread().ident == self.__thread_ident:
return self._cluster_info_state_get('timeline'), self._cluster_info_state_get('wal_position')
with self.connection().cursor() as cursor:
cursor.execute(cluster_info_query.format(self.wal_name, self.lsn_name))
return cursor.fetchone()[:2]
def postmaster_start_time(self):
try:
cursor = self.query("SELECT pg_catalog.to_char(pg_catalog.pg_postmaster_start_time(),"
" 'YYYY-MM-DD HH24:MI:SS.MS TZ')")
return cursor.fetchone()[0]
except psycopg2.Error:
return None
def last_operation(self):
return str(self._cluster_info_state_get('wal_position'))
def configure_server_parameters(self):
self._major_version = self.get_major_version()
self.config.setup_server_parameters()
return True
def move_data_directory(self):
if os.path.isdir(self._data_dir) and not self.is_running():
try:
new_name = '{0}_{1}'.format(self._data_dir, time.strftime('%Y-%m-%d-%H-%M-%S'))
logger.info('renaming data directory to %s', new_name)
os.rename(self._data_dir, new_name)
except OSError:
logger.exception("Could not rename data directory %s", self._data_dir)
def remove_data_directory(self):
self.set_role('uninitialized')
logger.info('Removing data directory: %s', self._data_dir)
try:
if os.path.islink(self._data_dir):
os.unlink(self._data_dir)
elif not os.path.exists(self._data_dir):
return
elif os.path.isfile(self._data_dir):
os.remove(self._data_dir)
elif os.path.isdir(self._data_dir):
# let's see if pg_xlog|pg_wal is a symlink, in this case we
# should clean the target
for pg_wal_dir in ('pg_xlog', 'pg_wal'):
pg_wal_path = os.path.join(self._data_dir, pg_wal_dir)
if os.path.exists(pg_wal_path) and os.path.islink(pg_wal_path):
pg_wal_realpath = os.path.realpath(pg_wal_path)
logger.info('Removing WAL directory: %s', pg_wal_realpath)
shutil.rmtree(pg_wal_realpath)
shutil.rmtree(self._data_dir)
except (IOError, OSError):
logger.exception('Could not remove data directory %s', self._data_dir)
self.move_data_directory()
def pick_synchronous_standby(self, cluster):
"""Finds the best candidate to be the synchronous standby.
Current synchronous standby is always preferred, unless it has disconnected or does not want to be a
synchronous standby any longer.
:returns tuple of candidate name or None, and bool showing if the member is the active synchronous standby.
"""
current = cluster.sync.sync_standby
current = current.lower() if current else current
members = {m.name.lower(): m for m in cluster.members}
candidates = []
# Pick candidates based on who has flushed WAL farthest.
# TODO: for synchronous_commit = remote_write we actually want to order on write_location
for app_name, state, sync_state in self.query(
"SELECT pg_catalog.lower(application_name), state, sync_state"
" FROM pg_catalog.pg_stat_replication"
" ORDER BY flush_{0} DESC".format(self.lsn_name)):
member = members.get(app_name)
if state != 'streaming' or not member or member.tags.get('nosync', False):
continue
if sync_state == 'sync':
return app_name, True
if sync_state == 'potential' and app_name == current:
# Prefer current even if not the best one any more to avoid indecisivness and spurious swaps.
return current, False
if sync_state in ('async', 'potential'):
candidates.append(app_name)
if candidates:
return candidates[0], False
return None, False
def read_postmaster_opts(self):
"""returns the list of option names/values from postgres.opts, Empty dict if read failed or no file"""
result = {}
try:
with open(os.path.join(self._data_dir, 'postmaster.opts')) as f:
data = f.read()
for opt in data.split('" "'):
if '=' in opt and opt.startswith('--'):
name, val = opt.split('=', 1)
result[name.strip('-')] = val.rstrip('"\n')
except IOError:
logger.exception('Error when reading postmaster.opts')
return result
def single_user_mode(self, command=None, options=None):
"""run a given command in a single-user mode. If the command is empty - then just start and stop"""
cmd = [self.pgcommand('postgres'), '--single', '-D', self._data_dir]
for opt, val in sorted((options or {}).items()):
cmd.extend(['-c', '{0}={1}'.format(opt, val)])
# need a database name to connect
cmd.append(self._database)
return self.cancellable.call(cmd, communicate_input=command)
def cleanup_archive_status(self):
status_dir = os.path.join(self._data_dir, 'pg_' + self.wal_name, 'archive_status')
try:
for f in os.listdir(status_dir):
path = os.path.join(status_dir, f)
try:
if os.path.islink(path):
os.unlink(path)
elif os.path.isfile(path):
os.remove(path)
except OSError:
logger.exception('Unable to remove %s', path)
except OSError:
logger.exception('Unable to list %s', status_dir)
def fix_cluster_state(self):
self.cleanup_archive_status()
# Start in a single user mode and stop to produce a clean shutdown
opts = self.read_postmaster_opts()
opts.update({'archive_mode': 'on', 'archive_command': 'false'})
self.config.remove_recovery_conf()
return self.single_user_mode(options=opts) == 0 or None
def schedule_sanity_checks_after_pause(self):
"""
After coming out of pause we have to:
1. sync replication slots, because it might happen that slots were removed
2. get new 'Database system identifier' to make sure that it wasn't changed
"""
self.slots_handler.schedule()
self._sysid = None
+385
View File
@@ -0,0 +1,385 @@
import logging
import os
import shlex
import tempfile
import time
from patroni.dcs import RemoteMember
from patroni.utils import deep_compare, uri
from six import string_types
from six.moves.urllib.parse import quote_plus
logger = logging.getLogger(__name__)
class Bootstrap(object):
def __init__(self, postgresql):
self._postgresql = postgresql
self._running_custom_bootstrap = False
@property
def running_custom_bootstrap(self):
return self._running_custom_bootstrap
@property
def keep_existing_recovery_conf(self):
return self._running_custom_bootstrap and self._keep_existing_recovery_conf
@staticmethod
def process_user_options(tool, options, not_allowed_options, error_handler):
user_options = []
def option_is_allowed(name):
ret = name not in not_allowed_options
if not ret:
error_handler('{0} option for {1} is not allowed'.format(name, tool))
return ret
if isinstance(options, dict):
for k, v in options.items():
if k and v:
user_options.append('--{0}={1}'.format(k, v))
elif isinstance(options, list):
for opt in options:
if isinstance(opt, string_types) and option_is_allowed(opt):
user_options.append('--{0}'.format(opt))
elif isinstance(opt, dict):
keys = list(opt.keys())
if len(keys) != 1 or not isinstance(opt[keys[0]], string_types) or not option_is_allowed(keys[0]):
error_handler('Error when parsing {0} key-value option {1}: only one key-value is allowed'
' and value should be a string'.format(tool, opt[keys[0]]))
user_options.append('--{0}={1}'.format(keys[0], opt[keys[0]]))
else:
error_handler('Error when parsing {0} option {1}: value should be string value'
' or a single key-value pair'.format(tool, opt))
else:
error_handler('{0} options must be list ot dict'.format(tool))
return user_options
def _initdb(self, config):
self._postgresql.set_state('initalizing new cluster')
not_allowed_options = ('pgdata', 'nosync', 'pwfile', 'sync-only', 'version')
def error_handler(e):
raise Exception(e)
options = self.process_user_options('initdb', config or [], not_allowed_options, error_handler)
pwfile = None
if self._postgresql.config.superuser:
if 'username' in self._postgresql.config.superuser:
options.append('--username={0}'.format(self._postgresql.config.superuser['username']))
if 'password' in self._postgresql.config.superuser:
(fd, pwfile) = tempfile.mkstemp()
os.write(fd, self._postgresql.config.superuser['password'].encode('utf-8'))
os.close(fd)
options.append('--pwfile={0}'.format(pwfile))
options = ['-o', ' '.join(options)] if options else []
ret = self._postgresql.pg_ctl('initdb', *options)
if pwfile:
os.remove(pwfile)
if ret:
self._postgresql.configure_server_parameters()
else:
self._postgresql.set_state('initdb failed')
return ret
def _post_restore(self):
self._postgresql.config.restore_configuration_files()
self._postgresql.configure_server_parameters()
# make sure there is no trigger file or postgres will be automatically promoted
trigger_file = 'promote_trigger_file' if self._postgresql.major_version >= 120000 else 'trigger_file'
trigger_file = self._postgresql.config.get('recovery_conf', {}).get(trigger_file) or 'promote'
trigger_file = os.path.abspath(os.path.join(self._postgresql.data_dir, trigger_file))
if os.path.exists(trigger_file):
os.unlink(trigger_file)
def _custom_bootstrap(self, config):
self._postgresql.set_state('running custom bootstrap script')
params = ['--scope=' + self._postgresql.scope, '--datadir=' + self._postgresql.data_dir]
try:
logger.info('Running custom bootstrap script: %s', config['command'])
if self._postgresql.cancellable.call(shlex.split(config['command']) + params) != 0:
self._postgresql.set_state('custom bootstrap failed')
return False
except Exception:
logger.exception('Exception during custom bootstrap')
return False
self._post_restore()
if 'recovery_conf' in config:
self._postgresql.config.write_recovery_conf(config['recovery_conf'])
elif not self.keep_existing_recovery_conf:
self._postgresql.config.remove_recovery_conf()
return True
def call_post_bootstrap(self, config):
"""
runs a script after initdb or custom bootstrap script is called and waits until completion.
"""
cmd = config.get('post_bootstrap') or config.get('post_init')
if cmd:
r = self._postgresql.config.local_connect_kwargs
if 'host' 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
# A host name of localhost matches both TCP (host name localhost) and Unix domain socket
# (pghost empty or the default socket directory) connections coming from the local machine.
r['host'] = 'localhost' # set it to localhost to write into pgpass
if 'user' in r:
user = r['user']
else:
user = ''
if 'password' in r:
import getpass
r.setdefault('user', os.environ.get('PGUSER', getpass.getuser()))
connstring = uri('postgres', (host, r['port']), r['database'], user)
env = self._postgresql.write_pgpass(r) if 'password' in r else None
try:
ret = self._postgresql.cancellable.call(shlex.split(cmd) + [connstring], env=env)
except OSError:
logger.error('post_init script %s failed', cmd)
return False
if ret != 0:
logger.error('post_init script %s returned non-zero code %d', cmd, ret)
return False
return True
def create_replica(self, clone_member):
"""
create the replica according to the replica_method
defined by the user. this is a list, so we need to
loop through all methods the user supplies
"""
self._postgresql.set_state('creating replica')
self._postgresql.schedule_sanity_checks_after_pause()
is_remote_master = isinstance(clone_member, RemoteMember)
# get list of replica methods either from clone member or from
# the config. If there is no configuration key, or no value is
# specified, use basebackup
replica_methods = (clone_member.create_replica_methods if is_remote_master
else self._postgresql.create_replica_methods) or ['basebackup']
if clone_member and clone_member.conn_url:
r = clone_member.conn_kwargs(self._postgresql.config.replication)
connstring = uri('postgres', (r['host'], r['port']), r['database'], r['user'])
# add the credentials to connect to the replica origin to pgpass.
env = self._postgresql.write_pgpass(r)
else:
connstring = ''
env = os.environ.copy()
# if we don't have any source, leave only replica methods that work without it
replica_methods = [r for r in replica_methods
if self._postgresql.replica_method_can_work_without_replication_connection(r)]
# go through them in priority order
ret = 1
for replica_method in replica_methods:
if self._postgresql.cancellable.is_cancelled:
break
method_config = self._postgresql.replica_method_options(replica_method)
# if the method is basebackup, then use the built-in
if replica_method == "basebackup":
ret = self.basebackup(connstring, env, method_config)
if ret == 0:
logger.info("replica has been created using basebackup")
# if basebackup succeeds, exit with success
break
else:
if not self._postgresql.data_directory_empty():
if method_config.get('keep_data', False):
logger.info('Leaving data directory uncleaned')
else:
self._postgresql.remove_data_directory()
cmd = replica_method
# user-defined method; check for configuration
# not required, actually
if method_config:
# look to see if the user has supplied a full command path
# if not, use the method name as the command
cmd = method_config.pop('command', cmd)
# add the default parameters
if not method_config.get('no_params', False):
method_config.update({"scope": self._postgresql.scope,
"role": "replica",
"datadir": self._postgresql.data_dir,
"connstring": connstring})
else:
for param in ('no_params', 'no_master', 'keep_data'):
method_config.pop(param, None)
params = ["--{0}={1}".format(arg, val) for arg, val in method_config.items()]
try:
# call script with the full set of parameters
ret = self._postgresql.cancellable.call(shlex.split(cmd) + params, env=env)
# if we succeeded, stop
if ret == 0:
logger.info('replica has been created using %s', replica_method)
break
else:
logger.error('Error creating replica using method %s: %s exited with code=%s',
replica_method, cmd, ret)
except Exception:
logger.exception('Error creating replica using method %s', replica_method)
ret = 1
self._postgresql.set_state('stopped')
return ret
def basebackup(self, conn_url, env, options):
# creates a replica data dir using pg_basebackup.
# this is the default, built-in create_replica_methods
# tries twice, then returns failure (as 1)
# uses "stream" as the xlog-method to avoid sync issues
# supports additional user-supplied options, those are not validated
maxfailures = 2
ret = 1
not_allowed_options = ('pgdata', 'format', 'wal-method', 'xlog-method', 'gzip',
'version', 'compress', 'dbname', 'host', 'port', 'username', 'password')
user_options = self.process_user_options('basebackup', options, not_allowed_options, logger.error)
for bbfailures in range(0, maxfailures):
if self._postgresql.cancellable.is_cancelled:
break
if not self._postgresql.data_directory_empty():
self._postgresql.remove_data_directory()
try:
ret = self._postgresql.cancellable.call([self._postgresql.pgcommand('pg_basebackup'),
'--pgdata=' + self._postgresql.data_dir, '-X', 'stream',
'--dbname=' + conn_url] + user_options, env=env)
if ret == 0:
break
else:
logger.error('Error when fetching backup: pg_basebackup exited with code=%s', ret)
except Exception as e:
logger.error('Error when fetching backup with pg_basebackup: %s', e)
if bbfailures < maxfailures - 1:
logger.warning('Trying again in 5 seconds')
time.sleep(5)
return ret
def clone(self, clone_member):
"""
- initialize the replica from an existing member (master or replica)
- initialize the replica using the replica creation method that
works without the replication connection (i.e. restore from on-disk
base backup)
"""
ret = self.create_replica(clone_member) == 0
if ret:
self._post_restore()
return ret
def bootstrap(self, config):
""" Initialize a new node from scratch and start it. """
pg_hba = config.get('pg_hba', [])
method = config.get('method') or 'initdb'
if method != 'initdb' and method in config and 'command' in config[method]:
self._keep_existing_recovery_conf = config[method].get('keep_existing_recovery_conf')
self._running_custom_bootstrap = True
do_initialize = self._custom_bootstrap
else:
method = 'initdb'
do_initialize = self._initdb
return do_initialize(config.get(method)) and self._postgresql.config.append_pg_hba(pg_hba) \
and self._postgresql.config.save_configuration_files() and self._postgresql.start()
def create_or_update_role(self, name, password, options):
options = list(map(str.upper, options))
if 'NOLOGIN' not in options and 'LOGIN' not in options:
options.append('LOGIN')
params = [name]
if password:
options.extend(['PASSWORD', '%s'])
params.extend([password, password])
sql = """DO $$
BEGIN
SET local synchronous_commit = 'local';
PERFORM * FROM pg_authid WHERE rolname = %s;
IF FOUND THEN
ALTER ROLE "{0}" WITH {1};
ELSE
CREATE ROLE "{0}" WITH {1};
END IF;
END;$$""".format(name, ' '.join(options))
self._postgresql.query(sql, *params)
def post_bootstrap(self, config, task):
try:
postgresql = self._postgresql
superuser = postgresql.config.superuser
if 'username' in superuser and 'password' in superuser:
self.create_or_update_role(superuser['username'], superuser['password'], ['SUPERUSER'])
task.complete(self.call_post_bootstrap(config))
if task.result:
replication = postgresql.config.replication
self.create_or_update_role(replication['username'], replication.get('password'), ['REPLICATION'])
rewind = postgresql.config.rewind_credentials
if not deep_compare(rewind, superuser):
self.create_or_update_role(rewind['username'], rewind.get('password'), [])
for f in ('pg_ls_dir(text, boolean, boolean)', 'pg_stat_file(text, boolean)',
'pg_read_binary_file(text)', 'pg_read_binary_file(text, bigint, bigint, boolean)'):
sql = """DO $$
BEGIN
SET local synchronous_commit = 'local';
GRANT EXECUTE ON function pg_catalog.{0} TO "{1}";
END;$$""".format(f, rewind['username'])
postgresql.query(sql)
for name, value in (config.get('users') or {}).items():
if all(name != a.get('username') for a in (superuser, replication, rewind)):
self.create_or_update_role(name, value.get('password'), value.get('options', []))
# We were doing a custom bootstrap instead of running initdb, therefore we opened trust
# access from certain addresses to be able to reach cluster and change password
if self._running_custom_bootstrap:
self._running_custom_bootstrap = False
# If we don't have custom configuration for pg_hba.conf we need to restore original file
if not postgresql.config.get('pg_hba'):
os.unlink(postgresql.config.pg_hba_conf)
postgresql.config.restore_configuration_files()
postgresql.config.write_postgresql_conf()
postgresql.config.replace_pg_ident()
# at this point there should be no recovery.conf
postgresql.config.remove_recovery_conf()
if postgresql.config.hba_file and postgresql.config.hba_file != postgresql.config.pg_hba_conf:
postgresql.restart()
else:
postgresql.config.replace_pg_hba()
if postgresql.pending_restart:
postgresql.restart()
else:
postgresql.reload()
time.sleep(1) # give a time to postgres to "reload" configuration files
postgresql.connection().close() # close connection to reconnect with a new password
except Exception:
logger.exception('post_bootstrap')
task.complete(False)
return task.result
@@ -19,8 +19,11 @@ class CallbackExecutor(Thread):
def call(self, cmd): def call(self, cmd):
with self._lock: with self._lock:
if self._process and self._process.poll() is None: if self._process and self._process.poll() is None:
self._process.kill() try:
logger.warning('Killed the old callback process because it was still running: %s', self._cmd) self._process.kill()
logger.warning('Killed the old callback process because it was still running: %s', self._cmd)
except OSError:
logger.exception('Failed to kill the old callback')
self._cmd = cmd self._cmd = cmd
self._callback_event.set() self._callback_event.set()
+76
View File
@@ -0,0 +1,76 @@
import logging
import os
import subprocess
from patroni.exceptions import PostgresException
from patroni.utils import polling_loop
from six import string_types
from threading import Lock
logger = logging.getLogger(__name__)
class CancellableSubprocess(object):
def __init__(self):
self._is_cancelled = False
self._process = None
self._lock = Lock()
def call(self, *args, **kwargs):
for s in ('stdin', 'stdout', 'stderr'):
kwargs.pop(s, None)
communicate_input = 'communicate_input' in kwargs
if communicate_input:
input_data = kwargs.pop('communicate_input', None)
if not isinstance(input_data, string_types):
input_data = ''
if input_data and input_data[-1] != '\n':
input_data += '\n'
kwargs['stdin'] = subprocess.PIPE
kwargs['stdout'] = open(os.devnull, 'w')
kwargs['stderr'] = subprocess.STDOUT
try:
with self._lock:
if self._is_cancelled:
raise PostgresException('cancelled')
self._is_cancelled = False
self._process = subprocess.Popen(*args, **kwargs)
if communicate_input:
if input_data:
self._process.communicate(input_data)
self._process.stdin.close()
return self._process.wait()
finally:
with self._lock:
self._process = None
def reset_is_cancelled(self):
with self._lock:
self._is_cancelled = False
@property
def is_cancelled(self):
with self._lock:
return self._is_cancelled
def cancel(self):
with self._lock:
self._is_cancelled = True
if self._process is None or self._process.returncode is not None:
return
self._process.terminate()
for _ in polling_loop(10):
with self._lock:
if self._process is None or self._process.returncode is not None:
return
with self._lock:
if self._process is not None and self._process.returncode is None:
self._process.kill()
+763
View File
@@ -0,0 +1,763 @@
import logging
import os
import re
import shutil
import socket
import stat
from requests.structures import CaseInsensitiveDict
from six.moves.urllib_parse import urlparse, parse_qsl, unquote
from ..utils import compare_values, parse_bool, parse_int, split_host_port, uri
logger = logging.getLogger(__name__)
SYNC_STANDBY_NAME_RE = re.compile(r'^[A-Za-z_][A-Za-z_0-9\$]*$')
PARAMETER_RE = re.compile(r'([a-z_]+)\s*=\s*')
def quote_ident(value):
"""Very simplified version of quote_ident"""
return value if SYNC_STANDBY_NAME_RE.match(value) else '"' + value + '"'
def conninfo_uri_parse(dsn):
ret = {}
r = urlparse(dsn)
if r.username:
ret['user'] = r.username
if r.password:
ret['password'] = r.password
if r.path[1:]:
ret['dbname'] = r.path[1:]
hosts = []
ports = []
for netloc in r.netloc.split('@')[-1].split(','):
host = port = None
if '[' in netloc and ']' in netloc:
host = netloc.split(']')[0][1:]
tmp = netloc.split(':', 1)
if host is None:
host = tmp[0]
if len(tmp) == 2:
host, port = tmp
if host is not None:
hosts.append(host)
if port is not None:
ports.append(port)
if hosts:
ret['host'] = ','.join(hosts)
if ports:
ret['port'] = ','.join(ports)
ret = {name: unquote(value) for name, value in ret.items()}
ret.update({name: value for name, value in parse_qsl(r.query)})
if ret.get('ssl') == 'true':
del ret['ssl']
ret['sslmode'] = 'require'
return ret
def read_param_value(value, is_quoted=False):
length = len(value)
ret = ''
i = 0
while i < length:
if is_quoted:
if value[i] == "'":
return ret, i
elif value[i].isspace():
break
if value[i] == '\\':
i += 1
if i >= length:
break
ret += value[i]
i += 1
return (None, None) if is_quoted else (ret, i)
def conninfo_parse(dsn):
ret = {}
length = len(dsn)
i = 0
while i < length:
if dsn[i].isspace():
i += 1
continue
param_match = PARAMETER_RE.match(dsn[i:])
if not param_match:
return
param = param_match.group(1)
i += param_match.end()
if i >= length:
return
is_quoted = dsn[i] == "'"
i += int(is_quoted)
value, end = read_param_value(dsn[i:], is_quoted)
if value is None:
return
i += end + int(is_quoted)
ret[param] = value
return ret
def parse_dsn(value):
"""
Very simple equivalent of `psycopg2.extensions.parse_dsn` introduced in 2.7.0.
We are not using psycopg2 function in order to remain compatible with 2.5.4+.
There is one minor difference though, this function removes `dbname` from the result
and sets the sslmode` to `prefer` if it is not present in the connection string.
This is necessary to simplify comparison of the old and the new values.
>>> r = parse_dsn('postgresql://u%2Fse:pass@:%2f123,[%2Fhost2]/db%2Fsdf?application_name=mya%2Fpp&ssl=true')
>>> r == {'application_name': 'mya/pp', 'host': ',/host2', 'sslmode': 'require',\
'password': 'pass', 'port': '/123', 'user': 'u/se'}
True
>>> r = parse_dsn(" host = 'host' dbname = db\\ name requiressl=1 ")
>>> r == {'host': 'host', 'sslmode': 'require'}
True
>>> parse_dsn('requiressl = 0\\\\') == {'sslmode': 'prefer'}
True
>>> parse_dsn("host=a foo = '") is None
True
>>> parse_dsn("host=a foo = ") is None
True
>>> parse_dsn("1") is None
True
"""
if value.startswith('postgres://') or value.startswith('postgresql://'):
ret = conninfo_uri_parse(value)
else:
ret = conninfo_parse(value)
if ret:
if 'sslmode' not in ret: # allow sslmode to take precedence over requiressl
requiressl = ret.pop('requiressl', None)
if requiressl == '1':
ret['sslmode'] = 'require'
elif requiressl is not None:
ret['sslmode'] = 'prefer'
ret.setdefault('sslmode', 'prefer')
if 'dbname' in ret:
del ret['dbname']
return ret
def mtime(filename):
try:
return os.stat(filename).st_mtime
except OSError:
return None
class ConfigHandler(object):
# List of parameters which must be always passed to postmaster as command line options
# to make it not possible to change them with 'ALTER SYSTEM'.
# Some of these parameters have sane default value assigned and Patroni doesn't allow
# to decrease this value. E.g. 'wal_level' can't be lower then 'hot_standby' and so on.
# These parameters could be changed only globally, i.e. via DCS.
# P.S. 'listen_addresses' and 'port' are added here just for convenience, to mark them
# as a parameters which should always be passed through command line.
#
# Format:
# key - parameter name
# value - tuple(default_value, check_function, min_version)
# default_value -- some sane default value
# check_function -- if the new value is not correct must return `!False`
# min_version -- major version of PostgreSQL when parameter was introduced
CMDLINE_OPTIONS = CaseInsensitiveDict({
'listen_addresses': (None, lambda _: False, 90100),
'port': (None, lambda _: False, 90100),
'cluster_name': (None, lambda _: False, 90500),
'wal_level': ('hot_standby', lambda v: v.lower() in ('hot_standby', 'replica', 'logical'), 90100),
'hot_standby': ('on', lambda _: False, 90100),
'max_connections': (100, lambda v: int(v) >= 25, 90100),
'max_wal_senders': (10, lambda v: int(v) >= 3, 90100),
'wal_keep_segments': (8, lambda v: int(v) >= 1, 90100),
'max_prepared_transactions': (0, lambda v: int(v) >= 0, 90100),
'max_locks_per_transaction': (64, lambda v: int(v) >= 32, 90100),
'track_commit_timestamp': ('off', lambda v: parse_bool(v) is not None, 90500),
'max_replication_slots': (10, lambda v: int(v) >= 4, 90400),
'max_worker_processes': (8, lambda v: int(v) >= 2, 90400),
'wal_log_hints': ('on', lambda _: False, 90400)
})
_RECOVERY_PARAMETERS = {
'archive_cleanup_command',
'restore_command',
'recovery_end_command',
'recovery_target',
'recovery_target_name',
'recovery_target_time',
'recovery_target_xid',
'recovery_target_lsn',
'recovery_target_inclusive',
'recovery_target_timeline',
'recovery_target_action',
'recovery_min_apply_delay',
'primary_conninfo',
'primary_slot_name',
'promote_trigger_file',
'trigger_file'
}
_CONFIG_WARNING_HEADER = '# Do not edit this file manually!\n# It will be overwritten by Patroni!\n'
def __init__(self, postgresql, config):
self._postgresql = postgresql
self._config_dir = os.path.abspath(config.get('config_dir') or postgresql.data_dir)
config_base_name = config.get('config_base_name', 'postgresql')
self._postgresql_conf = os.path.join(self._config_dir, config_base_name + '.conf')
self._postgresql_conf_mtime = None
self._postgresql_base_conf_name = config_base_name + '.base.conf'
self._postgresql_base_conf = os.path.join(self._config_dir, self._postgresql_base_conf_name)
self._pg_hba_conf = os.path.join(self._config_dir, 'pg_hba.conf')
self._pg_ident_conf = os.path.join(self._config_dir, 'pg_ident.conf')
self._recovery_conf = os.path.join(postgresql.data_dir, 'recovery.conf')
self._recovery_conf_mtime = None
self._recovery_signal = os.path.join(postgresql.data_dir, 'recovery.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_mtime = None
self._synchronous_standby_names = None
self._postmaster_ctime = None
self._primary_conninfo = None
self._config = {}
self._recovery_params = {}
self.reload_config(config)
def setup_server_parameters(self):
self._server_parameters = self.get_server_parameters(self._config)
self._adjust_recovery_parameters()
@property
def _configuration_to_save(self):
configuration = [os.path.basename(self._postgresql_conf)]
if 'custom_conf' not in self._config:
configuration.append(os.path.basename(self._postgresql_base_conf_name))
if not self.hba_file:
configuration.append('pg_hba.conf')
if not self._server_parameters.get('ident_file'):
configuration.append('pg_ident.conf')
return configuration
def save_configuration_files(self, check_custom_bootstrap=False):
"""
copy postgresql.conf to postgresql.conf.backup to be able to retrive configuration files
- originally stored as symlinks, those are normally skipped by pg_basebackup
- in case of WAL-E basebackup (see http://comments.gmane.org/gmane.comp.db.postgresql.wal-e/239)
"""
if not (check_custom_bootstrap and self._postgresql.bootstrap.running_custom_bootstrap):
try:
for f in self._configuration_to_save:
config_file = os.path.join(self._config_dir, f)
backup_file = os.path.join(self._postgresql.data_dir, f + '.backup')
if os.path.isfile(config_file):
shutil.copy(config_file, backup_file)
except IOError:
logger.exception('unable to create backup copies of configuration files')
return True
def restore_configuration_files(self):
""" restore a previously saved postgresql.conf """
try:
for f in self._configuration_to_save:
config_file = os.path.join(self._config_dir, f)
backup_file = os.path.join(self._postgresql.data_dir, f + '.backup')
if not os.path.isfile(config_file):
if os.path.isfile(backup_file):
shutil.copy(backup_file, config_file)
# Previously we didn't backup pg_ident.conf, if file is missing just create empty
elif f == 'pg_ident.conf':
open(config_file, 'w').close()
except IOError:
logger.exception('unable to restore configuration files from backup')
def write_postgresql_conf(self, configuration=None):
# rename the original configuration if it is necessary
if 'custom_conf' not in self._config and not os.path.exists(self._postgresql_base_conf):
os.rename(self._postgresql_conf, self._postgresql_base_conf)
with open(self._postgresql_conf, 'w') as f:
os.chmod(self._postgresql_conf, stat.S_IWRITE | stat.S_IREAD)
f.write(self._CONFIG_WARNING_HEADER)
f.write("include '{0}'\n\n".format(self._config.get('custom_conf') or self._postgresql_base_conf_name))
for name, value in sorted((configuration or self._server_parameters).items()):
if (not self._postgresql.bootstrap.running_custom_bootstrap or name != 'hba_file') \
and name not in self._RECOVERY_PARAMETERS:
f.write("{0} = '{1}'\n".format(name, value))
# 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
# therefore we need to make sure that hba_file is not overriden
# after changing superuser password we will "revert" all these "changes"
if self._postgresql.bootstrap.running_custom_bootstrap or 'hba_file' not in self._server_parameters:
f.write("hba_file = '{0}'\n".format(self._pg_hba_conf.replace('\\', '\\\\')))
if 'ident_file' not in self._server_parameters:
f.write("ident_file = '{0}'\n".format(self._pg_ident_conf.replace('\\', '\\\\')))
if self._postgresql.major_version >= 120000:
if self._recovery_params:
f.write('\n# recovery.conf\n')
for name, value in sorted(self._recovery_params.items()):
f.write("{0} = '{1}'\n".format(name, value))
if not self._postgresql.bootstrap.keep_existing_recovery_conf:
self._sanitize_auto_conf()
def append_pg_hba(self, config):
if not self.hba_file and not self._config.get('pg_hba'):
with open(self._pg_hba_conf, 'a') as f:
f.write('\n{}\n'.format('\n'.join(config)))
return True
def replace_pg_hba(self):
"""
Replace pg_hba.conf content in the PGDATA if hba_file is not defined in the
`postgresql.parameters` and pg_hba is defined in `postgresql` configuration section.
:returns: True if pg_hba.conf was rewritten.
"""
# 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
if self._postgresql.bootstrap.running_custom_bootstrap:
addresses = {'': 'local'}
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(
self.local_replication_address['host'], self.local_replication_address['port'],
0, socket.SOCK_STREAM, socket.IPPROTO_TCP)})
with open(self._pg_hba_conf, 'w') as f:
f.write(self._CONFIG_WARNING_HEADER)
for address, t in addresses.items():
f.write((
'{0}\treplication\t{1}\t{3}\ttrust\n'
'{0}\tall\t{2}\t{3}\ttrust\n'
).format(t, self.replication['username'], self._superuser.get('username') or 'all', address))
elif not self.hba_file and self._config.get('pg_hba'):
with open(self._pg_hba_conf, 'w') as f:
f.write(self._CONFIG_WARNING_HEADER)
for line in self._config['pg_hba']:
f.write('{0}\n'.format(line))
return True
def replace_pg_ident(self):
"""
Replace pg_ident.conf content in the PGDATA if ident_file is not defined in the
`postgresql.parameters` and pg_ident is defined in the `postgresql` section.
:returns: True if pg_ident.conf was rewritten.
"""
if not self._server_parameters.get('ident_file') and self._config.get('pg_ident'):
with open(self._pg_ident_conf, 'w') as f:
f.write(self._CONFIG_WARNING_HEADER)
for line in self._config['pg_ident']:
f.write('{0}\n'.format(line))
return True
def primary_conninfo_params(self, member):
name = self._postgresql.name
if not (member and member.conn_url) or member.name == name:
return None
ret = member.conn_kwargs(self.replication)
ret.update(application_name=name, sslmode='prefer')
if self._krbsrvname:
ret['krbsrvname'] = self._krbsrvname
if 'database' in ret:
del ret['database']
return ret
def primary_conninfo(self, member):
r = self.primary_conninfo_params(member)
if not r:
return None
keywords = 'user password host port sslmode application_name krbsrvname'.split()
return ' '.join('{0}={{{0}}}'.format(kw) for kw in keywords if r.get(kw)).format(**r)
def recovery_conf_exists(self):
if self._postgresql.major_version >= 120000:
return os.path.exists(self._standby_signal) or os.path.exists(self._recovery_signal)
return os.path.exists(self._recovery_conf)
def _read_primary_conninfo(self):
pg_conf_mtime = mtime(self._postgresql_conf)
auto_conf_mtime = mtime(self._auto_conf)
postmaster_ctime = self._postgresql.is_running()
if postmaster_ctime:
postmaster_ctime = postmaster_ctime.create_time()
if self._postgresql_conf_mtime == pg_conf_mtime and self._auto_conf_mtime == auto_conf_mtime \
and self._postmaster_ctime == postmaster_ctime:
return None, False
try:
primary_conninfo = self._postgresql.query('SHOW primary_conninfo').fetchone()[0]
self._postgresql_conf_mtime = pg_conf_mtime
self._auto_conf_mtime = auto_conf_mtime
self._postmaster_ctime = postmaster_ctime
except Exception:
primary_conninfo = None
return primary_conninfo, True
def _read_primary_conninfo_pre_v12(self):
recovery_conf_mtime = mtime(self._recovery_conf)
if recovery_conf_mtime == self._recovery_conf_mtime:
return None, False
primary_conninfo = ''
with open(self._recovery_conf, 'r') as f:
for line in f:
match = PARAMETER_RE.match(line)
if match and match.group(1) == 'primary_conninfo':
i = match.end()
if i < len(line):
is_quoted = line[i] == "'"
i += int(is_quoted)
primary_conninfo, _ = read_param_value(line[i:], is_quoted)
self._recovery_conf_mtime = recovery_conf_mtime
return primary_conninfo, True
def check_recovery_conf(self, member): # Name is confusing. In fact it checks the value of primary_conninfo
# TODO: recovery.conf could be stale, would be nice to detect that.
if self._postgresql.major_version >= 120000:
if not os.path.exists(self._standby_signal):
return False
_read_primary_conninfo = self._read_primary_conninfo
else:
if not self.recovery_conf_exists():
return False
_read_primary_conninfo = self._read_primary_conninfo_pre_v12
primary_conninfo, updated = _read_primary_conninfo()
# updated indicates that mtime of postgresql.conf, postgresql.auto.conf, or recovery.conf was changed
# and the primary_conninfo value was read either from config or from the database connection.
if updated:
# primary_conninfo is one of:
# - None (exception or unparsable config)
# - '' (not in config)
# - or the actual dsn value
self._primary_conninfo = primary_conninfo
if primary_conninfo:
# We will cache parsed value until the next config change.
self._primary_conninfo = parse_dsn(primary_conninfo)
# If we failed to parse non-empty connection string this indicates that config if broken.
if not self._primary_conninfo:
return False
elif primary_conninfo is not None:
self._primary_conninfo = {}
else: # primary_conninfo is None, config is probably broken
return False
wanted_primary_conninfo = self.primary_conninfo_params(member)
# first we will cover corner cases, when we are replicating from somewhere while shouldn't
# or there is no primary_conninfo but we should replicate from some specific node.
if not wanted_primary_conninfo:
return not self._primary_conninfo
elif not self._primary_conninfo:
return False
return all(self._primary_conninfo.get(p) == str(v) for p, v in wanted_primary_conninfo.items())
@staticmethod
def _remove_file_if_exists(name):
if os.path.isfile(name) or os.path.islink(name):
os.unlink(name)
def write_recovery_conf(self, recovery_params):
if self._postgresql.major_version >= 120000:
if parse_bool(recovery_params.pop('standby_mode', None)):
open(self._standby_signal, 'w').close()
else:
self._remove_file_if_exists(self._standby_signal)
open(self._recovery_signal, 'w').close()
self._recovery_params = recovery_params
else:
with open(self._recovery_conf, 'w') as f:
os.chmod(self._recovery_conf, stat.S_IWRITE | stat.S_IREAD)
for name, value in recovery_params.items():
f.write("{0} = '{1}'\n".format(name, value))
def remove_recovery_conf(self):
for name in (self._recovery_conf, self._standby_signal, self._recovery_signal):
self._remove_file_if_exists(name)
self._recovery_params = {}
def _sanitize_auto_conf(self):
overwrite = False
lines = []
if os.path.exists(self._auto_conf):
try:
with open(self._auto_conf) as f:
for raw_line in f:
line = raw_line.strip()
match = PARAMETER_RE.match(line)
if match and match.group(1).lower() in self._RECOVERY_PARAMETERS:
overwrite = True
else:
lines.append(raw_line)
except Exception:
logger.info('Failed to read %s', self._auto_conf)
if overwrite:
try:
with open(self._auto_conf, 'w') as f:
for raw_line in lines:
f.write(raw_line)
except Exception:
logger.exception('Failed to remove some unwanted parameters from %s', self._auto_conf)
def _adjust_recovery_parameters(self):
# It is not strictly necessary, but we can make patroni configs crossi-compatible with all postgres versions.
recovery_conf = {n: v for n, v in self._server_parameters.items() if n.lower() in self._RECOVERY_PARAMETERS}
if recovery_conf:
self._config['recovery_conf'] = recovery_conf
if self.get('recovery_conf'):
good_name, bad_name = 'trigger_file', 'promote_trigger_file'
if self._postgresql.major_version >= 120000:
good_name, bad_name = bad_name, good_name
value = self._config['recovery_conf'].pop(bad_name, None)
if good_name not in self._config['recovery_conf'] and value:
self._config['recovery_conf'][good_name] = value
def get_server_parameters(self, config):
parameters = config['parameters'].copy()
listen_addresses, port = split_host_port(config['listen'], 5432)
parameters.update(cluster_name=self._postgresql.scope, listen_addresses=listen_addresses, port=str(port))
if config.get('synchronous_mode', False):
if self._synchronous_standby_names is None:
if config.get('synchronous_mode_strict', False):
parameters['synchronous_standby_names'] = '*'
else:
parameters.pop('synchronous_standby_names', None)
else:
parameters['synchronous_standby_names'] = self._synchronous_standby_names
if self._postgresql.major_version >= 90600 and parameters['wal_level'] == 'hot_standby':
parameters['wal_level'] = 'replica'
ret = CaseInsensitiveDict({k: v for k, v in parameters.items() if not self._postgresql.major_version or
self._postgresql.major_version >= self.CMDLINE_OPTIONS.get(k, (0, 1, 90100))[2]})
ret.update({k: os.path.join(self._config_dir, ret[k]) for k in ('hba_file', 'ident_file') if k in ret})
return ret
@staticmethod
def _get_unix_local_address(unix_socket_directories):
for d in unix_socket_directories.split(','):
d = d.strip()
if d.startswith('/'): # Only absolute path can be used to connect via unix-socket
return d
return ''
def _get_tcp_local_address(self):
listen_addresses = self._server_parameters['listen_addresses'].split(',')
for la in listen_addresses:
if la.strip().lower() in ('*', '0.0.0.0', '127.0.0.1', 'localhost'): # we are listening on '*' or localhost
return 'localhost' # connection via localhost is preferred
return listen_addresses[0].strip() # can't use localhost, take first address from listen_addresses
@property
def local_connect_kwargs(self):
ret = self._local_address.copy()
ret.update({'database': self._postgresql.database,
'fallback_application_name': 'Patroni',
'connect_timeout': 3,
'options': '-c statement_timeout=2000'})
if 'username' in self._superuser:
ret['user'] = self._superuser['username']
if 'password' in self._superuser:
ret['password'] = self._superuser['password']
return ret
def resolve_connection_addresses(self):
port = self._server_parameters['port']
tcp_local_address = self._get_tcp_local_address()
local_address = {'port': port}
if self._config.get('use_unix_socket'):
unix_socket_directories = self._server_parameters.get('unix_socket_directories')
if unix_socket_directories is not None:
# fallback to tcp if unix_socket_directories is set, but there are no sutable values
local_address['host'] = self._get_unix_local_address(unix_socket_directories) or tcp_local_address
# if unix_socket_directories is not specified, but use_unix_socket is set to true - do our best
# to use default value, i.e. don't specify a host neither in connection url nor arguments
else:
local_address['host'] = tcp_local_address
self._local_address = local_address
self.local_replication_address = {'host': tcp_local_address, 'port': port}
netloc = self._config.get('connect_address') or tcp_local_address + ':' + port
self._postgresql.connection_string = uri('postgres', netloc, self._postgresql.database)
self._postgresql.set_connection_kwargs(self.local_connect_kwargs)
def reload_config(self, config):
self._superuser = config['authentication'].get('superuser', {})
server_parameters = self.get_server_parameters(config)
conf_changed = hba_changed = ident_changed = local_connection_address_changed = pending_restart = False
if self._postgresql.state == 'running':
changes = CaseInsensitiveDict({p: v for p, v in server_parameters.items() if '.' not in p})
changes.update({p: None for p in self._server_parameters.keys() if not ('.' in p or p in changes)})
if changes:
# XXX: query can raise an exception
for r in self._postgresql.query(('SELECT name, setting, unit, vartype, context '
+ 'FROM pg_catalog.pg_settings ' +
' WHERE pg_catalog.lower(name) IN ('
+ ', '.join(['%s'] * len(changes)) +
')'), *(k.lower() for k in changes.keys())):
if r[4] != 'internal' and r[0] in changes:
new_value = changes.pop(r[0])
if new_value is None or not compare_values(r[3], r[2], r[1], new_value):
if r[4] == 'postmaster':
pending_restart = True
logger.info('Changed %s from %s to %s (restart required)', r[0], r[1], new_value)
if config.get('use_unix_socket') and r[0] == 'unix_socket_directories'\
or r[0] in ('listen_addresses', 'port'):
local_connection_address_changed = True
else:
logger.info('Changed %s from %s to %s', r[0], r[1], new_value)
conf_changed = True
for param in changes:
if param in server_parameters:
logger.warning('Removing invalid parameter `%s` from postgresql.parameters', param)
server_parameters.pop(param)
# Check that user-defined-paramters have changed (parameters with period in name)
if not conf_changed:
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
break
if not conf_changed:
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
break
if not server_parameters.get('hba_file') and config.get('pg_hba'):
hba_changed = self._config.get('pg_hba', []) != config['pg_hba']
if not server_parameters.get('ident_file') and config.get('pg_ident'):
ident_changed = self._config.get('pg_ident', []) != config['pg_ident']
self._config = config
self._postgresql.set_pending_restart(pending_restart)
self._server_parameters = server_parameters
self._adjust_recovery_parameters()
self._connect_address = config.get('connect_address')
self._krbsrvname = config.get('krbsrvname')
# for not so obvious connection attempts that may happen outside of pyscopg2
if self._krbsrvname:
os.environ['PGKRBSRVNAME'] = self._krbsrvname
if not local_connection_address_changed:
self.resolve_connection_addresses()
if conf_changed:
self.write_postgresql_conf()
if hba_changed:
self.replace_pg_hba()
if ident_changed:
self.replace_pg_ident()
if conf_changed or hba_changed or ident_changed:
logger.info('PostgreSQL configuration items changed, reloading configuration.')
self._postgresql.reload()
elif not pending_restart:
logger.info('No PostgreSQL configuration items changed, nothing to reload.')
def set_synchronous_standby(self, name):
"""Sets a node to be synchronous standby and if changed does a reload for PostgreSQL."""
if name and name != '*':
name = quote_ident(name)
if name != self._synchronous_standby_names:
if name is None:
self._server_parameters.pop('synchronous_standby_names', None)
else:
self._server_parameters['synchronous_standby_names'] = name
self._synchronous_standby_names = name
if self._postgresql.state == 'running':
self.write_postgresql_conf()
self._postgresql.reload()
@property
def effective_configuration(self):
"""It might happen that the current value of one (or more) below parameters stored in
the controldata is higher than the value stored in the global cluster configuration.
Example: max_connections in global configuration is 100, but in controldata
`Current max_connections setting: 200`. If we try to start postgres with
max_connections=100, it will immediately exit.
As a workaround we will start it with the values from controldata and set `pending_restart`
to true as an indicator that current values of parameters are not matching expectations."""
if self._postgresql.role == 'master':
return self._server_parameters
options_mapping = {
'max_connections': 'max_connections setting',
'max_prepared_transactions': 'max_prepared_xacts setting',
'max_locks_per_transaction': 'max_locks_per_xact setting'
}
if self._postgresql.major_version >= 90400:
options_mapping['max_worker_processes'] = 'max_worker_processes setting'
if self._postgresql.major_version >= 120000:
options_mapping['max_wal_senders'] = 'max_wal_senders setting'
data = self._postgresql.controldata()
effective_configuration = self._server_parameters.copy()
for name, cname in options_mapping.items():
value = parse_int(effective_configuration[name])
cvalue = parse_int(data[cname])
if cvalue > value:
effective_configuration[name] = cvalue
self._postgresql.set_pending_restart(True)
return effective_configuration
@property
def replication(self):
return self._config['authentication']['replication']
@property
def superuser(self):
return self._superuser
@property
def rewind_credentials(self):
return self._config['authentication'].get('rewind', self._superuser) \
if self._postgresql.major_version >= 110000 else self._superuser
@property
def hba_file(self):
return self._server_parameters.get('hba_file')
@property
def pg_hba_conf(self):
return self._pg_hba_conf
@property
def postgresql_conf(self):
return self._postgresql_conf
def get(self, key, default=None):
return self._config.get(key, default)
+46
View File
@@ -0,0 +1,46 @@
import logging
import psycopg2
from contextlib import contextmanager
from threading import Lock
logger = logging.getLogger(__name__)
class Connection(object):
def __init__(self):
self._lock = Lock()
self._connection = None
self._cursor_holder = None
def set_conn_kwargs(self, conn_kwargs):
self._conn_kwargs = conn_kwargs
def get(self):
with self._lock:
if not self._connection or self._connection.closed != 0:
self._connection = psycopg2.connect(**self._conn_kwargs)
self._connection.autocommit = True
self.server_version = self._connection.server_version
return self._connection
def cursor(self):
if not self._cursor_holder or self._cursor_holder.closed or self._cursor_holder.connection.closed != 0:
logger.info("establishing a new patroni connection to the postgres cluster")
self._cursor_holder = self.get().cursor()
return self._cursor_holder
def close(self):
if self._connection and self._connection.closed == 0:
self._connection.close()
logger.info("closed patroni connection to the postgresql cluster")
self._cursor_holder = self._connection = None
@contextmanager
def get_connection_cursor(**kwargs):
with psycopg2.connect(**kwargs) as conn:
conn.autocommit = True
with conn.cursor() as cur:
yield cur
+70
View File
@@ -0,0 +1,70 @@
import logging
from patroni.exceptions import PostgresException
logger = logging.getLogger(__name__)
def postgres_version_to_int(pg_version):
"""Convert the server_version to integer
>>> postgres_version_to_int('9.5.3')
90503
>>> postgres_version_to_int('9.3.13')
90313
>>> postgres_version_to_int('10.1')
100001
>>> postgres_version_to_int('10') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 10'
>>> postgres_version_to_int('9.6') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
PostgresException: 'Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: 9.6'
>>> postgres_version_to_int('a.b.c') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
PostgresException: 'Invalid PostgreSQL version: a.b.c'
"""
try:
components = list(map(int, pg_version.split('.')))
except ValueError:
raise PostgresException('Invalid PostgreSQL version: {0}'.format(pg_version))
if len(components) < 2 or len(components) == 2 and components[0] < 10 or len(components) > 3:
raise PostgresException('Invalid PostgreSQL version format: X.Y or X.Y.Z is accepted: {0}'.format(pg_version))
if len(components) == 2:
# new style verion numbers, i.e. 10.1 becomes 100001
components.insert(1, 0)
return int(''.join('{0:02d}'.format(c) for c in components))
def postgres_major_version_to_int(pg_version):
"""
>>> postgres_major_version_to_int('10')
100000
>>> postgres_major_version_to_int('9.6')
90600
"""
return postgres_version_to_int(pg_version + '.0')
def parse_lsn(lsn):
t = lsn.split('/')
return int(t[0], 16) * 0x100000000 + int(t[1], 16)
def parse_history(data):
for line in data.split('\n'):
values = line.strip().split('\t')
if len(values) == 3:
try:
values[0] = int(values[0])
values[1] = parse_lsn(values[1])
yield values
except (IndexError, ValueError):
logger.exception('Exception when parsing timeline history line "%s"', values)
+185
View File
@@ -0,0 +1,185 @@
import logging
import multiprocessing
import os
import psutil
import re
import signal
import subprocess
logger = logging.getLogger(__name__)
STOP_SIGNALS = {
'smart': signal.SIGTERM,
'fast': signal.SIGINT,
'immediate': signal.SIGQUIT if os.name != 'nt' else signal.SIGABRT,
}
def pg_ctl_start(conn, cmdline, env):
if os.name != 'nt':
os.setsid()
try:
postmaster = subprocess.Popen(cmdline, close_fds=True, env=env)
conn.send(postmaster.pid)
except Exception:
logger.exception('Failed to execute %s', cmdline)
conn.send(None)
conn.close()
class PostmasterProcess(psutil.Process):
def __init__(self, pid):
self.is_single_user = False
if pid < 0:
pid = -pid
self.is_single_user = True
super(PostmasterProcess, self).__init__(pid)
@staticmethod
def _read_postmaster_pidfile(data_dir):
"""Reads and parses postmaster.pid from the data directory
:returns dictionary of values if successful, empty dictionary otherwise
"""
pid_line_names = ['pid', 'data_dir', 'start_time', 'port', 'socket_dir', 'listen_addr', 'shmem_key']
try:
with open(os.path.join(data_dir, 'postmaster.pid')) as f:
return {name: line.rstrip('\n') for name, line in zip(pid_line_names, f)}
except IOError:
return {}
def _is_postmaster_process(self):
try:
start_time = int(self._postmaster_pid.get('start_time', 0))
if start_time and abs(self.create_time() - start_time) > 3:
logger.info('Process %s is not postmaster, too much difference between PID file start time %s and '
'process start time %s', self.pid, self.create_time(), start_time)
return False
except ValueError:
logger.warning('Garbage start time value in pid file: %r', self._postmaster_pid.get('start_time'))
# Extra safety check. The process can't be ourselves, our parent or our direct child.
if self.pid == os.getpid() or self.pid == os.getppid() or self.ppid() == os.getpid():
logger.info('Patroni (pid=%s, ppid=%s), "fake postmaster" (pid=%s, ppid=%s)',
os.getpid(), os.getppid(), self.pid, self.ppid())
return False
return True
@classmethod
def _from_pidfile(cls, data_dir):
postmaster_pid = PostmasterProcess._read_postmaster_pidfile(data_dir)
try:
pid = int(postmaster_pid.get('pid', 0))
if pid:
proc = cls(pid)
proc._postmaster_pid = postmaster_pid
return proc
except ValueError:
pass
@staticmethod
def from_pidfile(data_dir):
try:
proc = PostmasterProcess._from_pidfile(data_dir)
return proc if proc and proc._is_postmaster_process() else None
except psutil.NoSuchProcess:
return None
@classmethod
def from_pid(cls, pid):
try:
return cls(pid)
except psutil.NoSuchProcess:
return None
def signal_stop(self, mode):
"""Signal postmaster process to stop
:returns None if signaled, True if process is already gone, False if error
"""
if self.is_single_user:
logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid))
return False
try:
self.send_signal(STOP_SIGNALS[mode])
except psutil.NoSuchProcess:
return True
except psutil.AccessDenied as e:
logger.warning("Could not send stop signal to PostgreSQL (error: {0})".format(e))
return False
return None
def wait_for_user_backends_to_close(self):
# These regexps are cross checked against versions PostgreSQL 9.1 .. 11
aux_proc_re = re.compile("(?:postgres:)( .*:)? (?:(?:archiver|startup|autovacuum launcher|autovacuum worker|"
"checkpointer|logger|stats collector|wal receiver|wal writer|writer)(?: process )?|"
"walreceiver|wal sender process|walsender|walwriter|background writer|"
"logical replication launcher|logical replication worker for|bgworker:) ")
try:
children = self.children()
except psutil.Error:
return logger.debug('Failed to get list of postmaster children')
user_backends = []
user_backends_cmdlines = []
for child in children:
try:
cmdline = child.cmdline()[0]
if not aux_proc_re.match(cmdline):
user_backends.append(child)
user_backends_cmdlines.append(cmdline)
except psutil.NoSuchProcess:
pass
if user_backends:
logger.debug('Waiting for user backends %s to close', ', '.join(user_backends_cmdlines))
psutil.wait_procs(user_backends)
logger.debug("Backends closed")
@staticmethod
def start(pgcommand, data_dir, conf, options):
# Unfortunately `pg_ctl start` does not return postmaster pid to us. Without this information
# it is hard to know the current state of postgres startup, so we had to reimplement pg_ctl start
# in python. It will start postgres, wait for port to be open and wait until postgres will start
# accepting connections.
# Important!!! We can't just start postgres using subprocess.Popen, because in this case it
# will be our child for the rest of our live and we will have to take care of it (`waitpid`).
# So we will use the same approach as pg_ctl uses: start a new process, which will start postgres.
# This process will write postmaster pid to stdout and exit immediately. Now it's responsibility
# of init process to take care about postmaster.
# In order to make everything portable we can't use fork&exec approach here, so we will call
# ourselves and pass list of arguments which must be used to start postgres.
# On Windows, in order to run a side-by-side assembly the specified env must include a valid SYSTEMROOT.
env = {p: os.environ[p] for p in ('PATH', 'LD_LIBRARY_PATH', 'LC_ALL', 'LANG', 'SYSTEMROOT') if p in os.environ}
try:
proc = PostmasterProcess._from_pidfile(data_dir)
if proc and not proc._is_postmaster_process():
# Upon start postmaster process performs various safety checks if there is a postmaster.pid
# file in the data directory. Although Patroni already detected that the running process
# corresponding to the postmaster.pid is not a postmaster, the new postmaster might fail
# to start, because it thinks that postmaster.pid is already locked.
# Important!!! Unlink of postmaster.pid isn't an option, because it has a lot of nasty race conditions.
# Luckily there is a workaround to this problem, we can pass the pid from postmaster.pid
# in the `PG_GRANDPARENT_PID` environment variable and postmaster will ignore it.
logger.info("Telling pg_ctl that it is safe to ignore postmaster.pid for process %s", proc.pid)
env['PG_GRANDPARENT_PID'] = str(proc.pid)
except psutil.NoSuchProcess:
pass
cmdline = [pgcommand, '-D', data_dir, '--config-file={}'.format(conf)] + options
logger.debug("Starting postgres: %s", " ".join(cmdline))
parent_conn, child_conn = multiprocessing.Pipe(False)
proc = multiprocessing.Process(target=pg_ctl_start, args=(child_conn, cmdline, env))
proc.start()
pid = parent_conn.recv()
proc.join()
if pid is None:
return
logger.info('postmaster pid=%s', pid)
# TODO: In an extremely unlikely case, the process could have exited and the pid reassigned. The start
# initiation time is not accurate enough to compare to create time as start time would also likely
# be relatively close. We need the subprocess extract pid+start_time in a race free manner.
return PostmasterProcess.from_pid(pid)
+217
View File
@@ -0,0 +1,217 @@
import logging
import os
import subprocess
from patroni.dcs import Leader
from patroni.postgresql.connection import get_connection_cursor
from patroni.postgresql.misc import parse_history, parse_lsn
logger = logging.getLogger(__name__)
REWIND_STATUS = type('Enum', (), {'INITIAL': 0, 'CHECKPOINT': 1, 'CHECK': 2, 'NEED': 3,
'NOT_NEED': 4, 'SUCCESS': 5, 'FAILED': 6})
class Rewind(object):
def __init__(self, postgresql):
self._postgresql = postgresql
self.reset_state()
@staticmethod
def configuration_allows_rewind(data):
return data.get('wal_log_hints setting', 'off') == 'on' or data.get('Data page checksum version', '0') != '0'
@property
def can_rewind(self):
""" check if pg_rewind executable is there and that pg_controldata indicates
we have either wal_log_hints or checksums turned on
"""
# low-hanging fruit: check if pg_rewind configuration is there
if not self._postgresql.config.get('use_pg_rewind'):
return False
cmd = [self._postgresql.pgcommand('pg_rewind'), '--help']
try:
ret = subprocess.call(cmd, stdout=open(os.devnull, 'w'), stderr=subprocess.STDOUT)
if ret != 0: # pg_rewind is not there, close up the shop and go home
return False
except OSError:
return False
return self.configuration_allows_rewind(self._postgresql.controldata())
@property
def can_rewind_or_reinitialize_allowed(self):
return self._postgresql.config.get('remove_data_directory_on_diverged_timelines') or self.can_rewind
def trigger_check_diverged_lsn(self):
if self.can_rewind_or_reinitialize_allowed and self._state != REWIND_STATUS.NEED:
self._state = REWIND_STATUS.CHECK
def check_leader_is_not_in_recovery(self, **kwargs):
if not kwargs.get('database'):
kwargs['database'] = self._postgresql.database
try:
with get_connection_cursor(connect_timeout=3, options='-c statement_timeout=2000', **kwargs) as cur:
cur.execute('SELECT pg_catalog.pg_is_in_recovery()')
if not cur.fetchone()[0]:
return True
logger.info('Leader is still in_recovery and therefore can\'t be used for rewind')
except Exception:
return logger.exception('Exception when working with leader')
def _get_local_timeline_lsn_from_controldata(self):
timeline = lsn = None
data = self._postgresql.controldata()
try:
if data.get('Database cluster state') == 'shut down in recovery':
lsn = data.get('Minimum recovery ending location')
timeline = int(data.get("Min recovery ending loc's timeline"))
if lsn == '0/0' or timeline == 0: # it was a master when it crashed
data['Database cluster state'] = 'shut down'
if data.get('Database cluster state') == 'shut down':
lsn = data.get('Latest checkpoint location')
timeline = int(data.get("Latest checkpoint's TimeLineID"))
except (TypeError, ValueError):
logger.exception('Failed to get local timeline and lsn from pg_controldata output')
return timeline, lsn
def _get_local_timeline_lsn(self):
if self._postgresql.is_running(): # if postgres is running - get timeline and lsn from replication connection
timeline, lsn = self._postgresql.get_local_timeline_lsn_from_replication_connection()
else: # otherwise analyze pg_controldata output
timeline, lsn = self._get_local_timeline_lsn_from_controldata()
logger.info('Local timeline=%s lsn=%s', timeline, lsn)
return timeline, lsn
def _check_timeline_and_lsn(self, leader):
local_timeline, local_lsn = self._get_local_timeline_lsn()
if local_timeline is None or local_lsn is None:
return
if isinstance(leader, Leader):
if leader.member.data.get('role') != 'master':
return
# standby cluster
elif not self.check_leader_is_not_in_recovery(**leader.conn_kwargs(self._postgresql.config.replication)):
return
history = need_rewind = None
try:
with self._postgresql.get_replication_connection_cursor(**leader.conn_kwargs()) as cur:
cur.execute('IDENTIFY_SYSTEM')
master_timeline = cur.fetchone()[1]
logger.info('master_timeline=%s', master_timeline)
if local_timeline > master_timeline: # Not always supported by pg_rewind
need_rewind = True
elif master_timeline > 1:
cur.execute('TIMELINE_HISTORY %s', (master_timeline,))
history = bytes(cur.fetchone()[1]).decode('utf-8')
logger.info('master: history=%s', history)
else: # local_timeline == master_timeline == 1
need_rewind = False
except Exception:
return logger.exception('Exception when working with master via replication connection')
if history is not None:
for parent_timeline, switchpoint, _ in parse_history(history):
if parent_timeline == local_timeline:
try:
need_rewind = parse_lsn(local_lsn) >= switchpoint
except (IndexError, ValueError):
logger.exception('Exception when parsing lsn')
break
elif parent_timeline > local_timeline:
break
self._state = need_rewind and REWIND_STATUS.NEED or REWIND_STATUS.NOT_NEED
def rewind_or_reinitialize_needed_and_possible(self, leader):
if leader and leader.name != self._postgresql.name and leader.conn_url and self._state == REWIND_STATUS.CHECK:
self._check_timeline_and_lsn(leader)
return leader and leader.conn_url and self._state == REWIND_STATUS.NEED
def check_for_checkpoint_after_promote(self):
if self._state == REWIND_STATUS.INITIAL and self._postgresql.is_leader():
try:
timeline = int(self._postgresql.controldata().get("Latest checkpoint's TimeLineID"))
if self._postgresql.get_master_timeline() == timeline:
self._state = REWIND_STATUS.CHECKPOINT
except (TypeError, ValueError):
logger.exception('Failed to parse timeline from pg_controldata output')
def checkpoint_after_promote(self):
return self._state == REWIND_STATUS.CHECKPOINT
def pg_rewind(self, r):
# prepare pg_rewind connection
env = self._postgresql.write_pgpass(r)
env['PGOPTIONS'] = '-c statement_timeout=0'
dsn_attrs = [
('user', r.get('user')),
('host', r.get('host')),
('port', r.get('port')),
('dbname', r.get('database') or self._postgresql.database),
('sslmode', 'prefer'),
('sslcompression', '1'),
]
dsn = " ".join("{0}={1}".format(k, v) for k, v in dsn_attrs if v is not None)
logger.info('running pg_rewind from %s', dsn)
try:
return self._postgresql.cancellable.call([self._postgresql.pgcommand('pg_rewind'), '-D',
self._postgresql.data_dir, '--source-server', dsn], env=env) == 0
except OSError:
return False
def execute(self, leader):
if self._postgresql.is_running() and not self._postgresql.stop(checkpoint=False):
return logger.warning('Can not run pg_rewind because postgres is still running')
# prepare pg_rewind connection
r = leader.conn_kwargs(self._postgresql.config.rewind_credentials)
# 1. make sure that we are really trying to rewind from the master
# 2. make sure that pg_control contains the new timeline by:
# running a checkpoint or
# waiting until Patroni on the master will expose checkpoint_after_promote=True
checkpoint_status = leader.checkpoint_after_promote if isinstance(leader, Leader) else None
if checkpoint_status is None: # master still runs the old Patroni
leader_status = self._postgresql.checkpoint(leader.conn_kwargs(self._postgresql.config.superuser))
if leader_status:
return logger.warning('Can not use %s for rewind: %s', leader.name, leader_status)
elif not checkpoint_status:
return logger.info('Waiting for checkpoint on %s before rewind', leader.name)
elif not self.check_leader_is_not_in_recovery(**r):
return
if self.pg_rewind(r):
self._state = REWIND_STATUS.SUCCESS
elif not self.check_leader_is_not_in_recovery(**r):
logger.warning('Failed to rewind because master %s become unreachable', leader.name)
else:
logger.error('Failed to rewind from healty master: %s', leader.name)
for name in ('remove_data_directory_on_rewind_failure', 'remove_data_directory_on_diverged_timelines'):
if self._postgresql.config.get(name):
logger.warning('%s is set. removing...', name)
self._postgresql.remove_data_directory()
self._state = REWIND_STATUS.INITIAL
break
else:
self._state = REWIND_STATUS.FAILED
return False
def reset_state(self):
self._state = REWIND_STATUS.INITIAL
@property
def is_needed(self):
return self._state in (REWIND_STATUS.CHECK, REWIND_STATUS.NEED)
@property
def executed(self):
return self._state > REWIND_STATUS.NOT_NEED
@property
def failed(self):
return self._state == REWIND_STATUS.FAILED
+108
View File
@@ -0,0 +1,108 @@
import logging
from patroni.postgresql.connection import get_connection_cursor
from collections import defaultdict
logger = logging.getLogger(__name__)
def compare_slots(s1, s2):
return s1['type'] == s2['type'] and (s1['type'] == 'physical' or
s1['database'] == s2['database'] and s1['plugin'] == s2['plugin'])
class SlotsHandler(object):
def __init__(self, postgresql):
self._postgresql = postgresql
self._use_slots = postgresql.config.get('use_slots', True)
self._replication_slots = {} # already existing replication slots
self.schedule()
@property
def use_slots(self):
return self._use_slots and self._postgresql.major_version >= 90400
def _query(self, sql, *params):
return self._postgresql.query(sql, *params, retry=False)
def load_replication_slots(self):
if self.use_slots and self._schedule_load_slots:
replication_slots = {}
cursor = self._query('SELECT slot_name, slot_type, plugin, database FROM pg_catalog.pg_replication_slots')
for r in cursor:
value = {'type': r[1]}
if r[1] == 'logical':
value.update({'plugin': r[2], 'database': r[3]})
replication_slots[r[0]] = value
self._replication_slots = replication_slots
self._schedule_load_slots = False
def drop_replication_slot(self, name):
cursor = self._query(('SELECT pg_catalog.pg_drop_replication_slot(%s) WHERE EXISTS (SELECT 1 ' +
'FROM pg_catalog.pg_replication_slots WHERE slot_name = %s AND NOT active)'), name, name)
# In normal situation rowcount should be 1, otherwise either slot doesn't exists or it is still active
return cursor.rowcount == 1
def sync_replication_slots(self, cluster):
if self.use_slots:
try:
self.load_replication_slots()
slots = cluster.get_replication_slots(self._postgresql.name, self._postgresql.role)
# drop old replication slots which are not presented in desired slots
for name in set(self._replication_slots) - set(slots):
if not self.drop_replication_slot(name):
logger.error("Failed to drop replication slot '%s'", name)
self._schedule_load_slots = True
immediately_reserve = ', true' if self._postgresql.major_version >= 90600 else ''
logical_slots = defaultdict(dict)
for name, value in slots.items():
if name in self._replication_slots and not compare_slots(value, self._replication_slots[name]):
logger.info("Trying to drop replication slot '%s' because value is changing from %s to %s",
name, self._replication_slots[name], value)
if not self.drop_replication_slot(name):
logger.error("Failed to drop replication slot '%s'", name)
self._schedule_load_slots = True
continue
self._replication_slots.pop(name)
if name not in self._replication_slots:
if value['type'] == 'physical':
try:
self._query(("SELECT pg_catalog.pg_create_physical_replication_slot(%s{0})" +
" WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_replication_slots" +
" WHERE slot_type = 'physical' AND slot_name = %s)").format(
immediately_reserve), name, name)
except Exception:
logger.exception("Failed to create physical replication slot '%s'", name)
self._schedule_load_slots = True
elif value['type'] == 'logical' and name not in self._replication_slots:
logical_slots[value['database']][name] = value
# create new logical slots
for database, values in logical_slots.items():
conn_kwargs = self._postgresql.config.local_connect_kwargs
conn_kwargs['database'] = database
with get_connection_cursor(**conn_kwargs) as cur:
for name, value in values.items():
try:
cur.execute("SELECT pg_catalog.pg_create_logical_replication_slot(%s, %s)" +
" WHERE NOT EXISTS (SELECT 1 FROM pg_catalog.pg_replication_slots" +
" WHERE slot_type = 'logical' AND slot_name = %s)",
(name, value['plugin'], name))
except Exception:
logger.exception("Failed to create logical replication slot '%s' plugin='%s'",
name, value['plugin'])
self._schedule_load_slots = True
self._replication_slots = slots
except Exception:
logger.exception('Exception when changing replication slots')
self._schedule_load_slots = True
def schedule(self, value=None):
if value is None:
value = self.use_slots
self._schedule_load_slots = value
-127
View File
@@ -1,127 +0,0 @@
import logging
import os
import psutil
import re
import signal
import subprocess
from patroni import call_self
logger = logging.getLogger(__name__)
STOP_SIGNALS = {
'smart': signal.SIGTERM,
'fast': signal.SIGINT,
'immediate': signal.SIGQUIT,
}
class PostmasterProcess(psutil.Process):
def __init__(self, pid):
self.is_single_user = False
if pid < 0:
pid = -pid
self.is_single_user = True
super(PostmasterProcess, self).__init__(pid)
@classmethod
def from_pidfile(cls, pidfile):
try:
pid = int(pidfile.get('pid', 0))
if not pid:
return None
except ValueError:
return None
try:
proc = cls(pid)
except psutil.NoSuchProcess:
return None
try:
start_time = int(pidfile.get('start_time', 0))
if start_time and abs(proc.create_time() - start_time) > 3:
return None
except ValueError:
logger.warning("Garbage start time value in pid file: %r", pidfile.get('start_time'))
# Extra safety check. The process can't be ourselves, our parent or our direct child.
if proc.pid == os.getpid() or proc.pid == os.getppid() or proc.parent() == os.getpid():
return None
return proc
@classmethod
def from_pid(cls, pid):
try:
return cls(pid)
except psutil.NoSuchProcess:
return None
def signal_stop(self, mode):
"""Signal postmaster process to stop
:returns None if signaled, True if process is already gone, False if error
"""
if self.is_single_user:
logger.warning("Cannot stop server; single-user server is running (PID: {0})".format(self.pid))
return False
try:
self.send_signal(STOP_SIGNALS[mode])
except psutil.NoSuchProcess:
return True
except psutil.AccessDenied as e:
logger.warning("Could not send stop signal to PostgreSQL (error: {0})".format(e))
return False
return None
def wait_for_user_backends_to_close(self):
# These regexps are cross checked against versions PostgreSQL 9.1 .. 9.6
aux_proc_re = re.compile("(?:postgres:)( .*:)? (?:""(?:startup|logger|checkpointer|writer|wal writer|"
"autovacuum launcher|autovacuum worker|stats collector|wal receiver|archiver|"
"wal sender) process|bgworker: )")
try:
user_backends = []
user_backends_cmdlines = []
for child in self.children():
try:
cmdline = child.cmdline()[0]
if not aux_proc_re.match(cmdline):
user_backends.append(child)
user_backends_cmdlines.append(cmdline)
except psutil.NoSuchProcess:
pass
if user_backends:
logger.debug('Waiting for user backends %s to close', ', '.join(user_backends_cmdlines))
psutil.wait_procs(user_backends)
logger.debug("Backends closed")
except psutil.Error:
logger.exception('wait_for_user_backends_to_close')
@classmethod
def start(cls, pgcommand, data_dir, conf, options):
# Unfortunately `pg_ctl start` does not return postmaster pid to us. Without this information
# it is hard to know the current state of postgres startup, so we had to reimplement pg_ctl start
# in python. It will start postgres, wait for port to be open and wait until postgres will start
# accepting connections.
# Important!!! We can't just start postgres using subprocess.Popen, because in this case it
# will be our child for the rest of our live and we will have to take care of it (`waitpid`).
# So we will use the same approach as pg_ctl uses: start a new process, which will start postgres.
# This process will write postmaster pid to stdout and exit immediately. Now it's responsibility
# of init process to take care about postmaster.
# In order to make everything portable we can't use fork&exec approach here, so we will call
# ourselves and pass list of arguments which must be used to start postgres.
proc = call_self(['pg_ctl_start', pgcommand, '-D', data_dir,
'--config-file={}'.format(conf)] + options, close_fds=True,
preexec_fn=os.setsid, stdout=subprocess.PIPE,
env={p: os.environ[p] for p in ('PATH', 'LC_ALL', 'LANG') if p in os.environ})
pid = int(proc.stdout.readline().strip())
proc.wait()
logger.info('postmaster pid=%s', pid)
# TODO: In an extremely unlikely case, the process could have exited and the pid reassigned. The start
# initiation time is not accurate enough to compare to create time as start time would also likely
# be relatively close. We need the subprocess extract pid+start_time in a race free manner.
return PostmasterProcess.from_pid(pid)
+6 -7
View File
@@ -224,13 +224,12 @@ class WALERestore(object):
lsn_name = 'location' lsn_name = 'location'
con.autocommit = True con.autocommit = True
with con.cursor() as cur: with con.cursor() as cur:
cur.execute("""SELECT CASE WHEN pg_is_in_recovery() cur.execute(("SELECT CASE WHEN pg_catalog.pg_is_in_recovery()"
THEN GREATEST( " THEN GREATEST(pg_catalog.pg_{0}_{1}_diff(COALESCE("
pg_{0}_{1}_diff(COALESCE( "pg_last_{0}_receive_{1}(), '0/0'), %s)::bigint, "
pg_last_{0}_receive_{1}(), '0/0'), %s)::bigint, "pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_last_{0}_replay_{1}(), %s)::bigint)"
pg_{0}_{1}_diff(pg_last_{0}_replay_{1}(), %s)::bigint) " ELSE pg_catalog.pg_{0}_{1}_diff(pg_catalog.pg_current_{0}_{1}(), %s)::bigint"
ELSE pg_{0}_{1}_diff(pg_current_{0}_{1}(), %s)::bigint " END").format(wal_name, lsn_name),
END""".format(wal_name, lsn_name),
(backup_start_lsn, backup_start_lsn, backup_start_lsn)) (backup_start_lsn, backup_start_lsn, backup_start_lsn))
diff_in_bytes = int(cur.fetchone()[0]) diff_in_bytes = int(cur.fetchone()[0])
+134 -63
View File
@@ -1,4 +1,6 @@
import logging
import random import random
import re
import time import time
from dateutil import tz from dateutil import tz
@@ -6,6 +8,13 @@ from patroni.exceptions import PatroniException
tzutc = tz.tzutc() tzutc = tz.tzutc()
logger = logging.getLogger(__name__)
OCT_RE = re.compile(r'^[-+]?0[0-7]*')
DEC_RE = re.compile(r'^[-+]?(0|[1-9][0-9]*)')
HEX_RE = re.compile(r'^[-+]?0x[0-9a-fA-F]+')
DBL_RE = re.compile(r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?')
def deep_compare(obj1, obj2): def deep_compare(obj1, obj2):
""" """
@@ -88,42 +97,77 @@ def strtol(value, strict=True):
True True
>>> strtol(' d ') == (None, 'd') >>> strtol(' d ') == (None, 'd')
True True
>>> strtol(' 1 d ') == (1, ' d')
True
>>> strtol('9s', False) == (9, 's') >>> strtol('9s', False) == (9, 's')
True True
>>> strtol(' s ', False) == (1, 's') >>> strtol(' s ', False) == (1, 's')
True True
""" """
value = str(value).strip() value = str(value).strip()
ln = len(value) for regex, base in ((HEX_RE, 16), (OCT_RE, 8), (DEC_RE, 10)):
i = 0 match = regex.match(value)
# skip sign: if match:
if i < ln and value[i] in ('-', '+'): end = match.end()
i += 1 return int(value[:end], base), value[end:]
return (None if strict else 1), value
# we always expect to get digit in the beginning
if i < ln and value[i].isdigit():
if value[i] == '0':
i += 1
if i < ln and value[i] in ('x', 'X'): # '0' followed by 'x': HEX
base = 16
i += 1
else: # just starts with '0': OCT
base = 8
else: # any other digit: DEC
base = 10
ret = None def strtod(value):
while i <= ln: """As most as possible close equivalent of strtod(3) function used by postgres to parse parameter values.
try: # try to find maximally long number >>> strtod(' A ') == (None, 'A')
i += 1 # by giving to `int` longer and longer strings True
ret = int(value[:i], base) """
except ValueError: # until we will not get an exception or end of the string value = str(value).strip()
i -= 1 match = DBL_RE.match(value)
break if match:
if ret is not None: # yay! there is a number in the beginning of the string end = match.end()
return ret, value[i:].strip() # return the number and the "rest" return float(value[:end]), value[end:]
return None, value
return (None if strict else 1), value.strip()
def rint(value):
"""
>>> rint(0.5) == 0
True
>>> rint(0.501) == 1
True
>>> rint(1.5) == 2
True
"""
ret = round(value)
return 2.0 * round(value / 2.0) if abs(ret - value) == 0.5 else ret
def convert_to_base_unit(value, unit, base_unit):
convert = {
'B': {'B': 1, 'kB': 1024, 'MB': 1024 * 1024, 'GB': 1024 * 1024 * 1024, 'TB': 1024 * 1024 * 1024 * 1024},
'kB': {'B': 1.0 / 1024, 'kB': 1, 'MB': 1024, 'GB': 1024 * 1024, 'TB': 1024 * 1024 * 1024},
'MB': {'B': 1.0 / (1024 * 1024), 'kB': 1.0 / 1024, 'MB': 1, 'GB': 1024, 'TB': 1024 * 1024},
'ms': {'us': 1.0 / 1000, 'ms': 1, 's': 1000, 'min': 1000 * 60, 'h': 1000 * 60 * 60, 'd': 1000 * 60 * 60 * 24},
's': {'us': 1.0 / (1000 * 1000), 'ms': 1.0 / 1000, 's': 1, 'min': 60, 'h': 60 * 60, 'd': 60 * 60 * 24},
'min': {'us': 1.0 / (1000 * 1000 * 60), 'ms': 1.0 / (1000 * 60), 's': 1.0 / 60, 'min': 1, 'h': 60, 'd': 60 * 24}
}
round_order = {
'TB': 'GB', 'GB': 'MB', 'MB': 'kB', 'kB': 'B',
'd': 'h', 'h': 'min', 'min': 's', 's': 'ms', 'ms': 'us'
}
if base_unit and base_unit not in convert:
base_value, base_unit = strtol(base_unit, False)
else:
base_value = 1
if base_unit in convert and unit in convert[base_unit]:
value *= convert[base_unit][unit] / float(base_value)
if unit in round_order:
multiplier = convert[base_unit][round_order[unit]]
value = rint(value / float(multiplier)) * multiplier
return value
def parse_int(value, base_unit=None): def parse_int(value, base_unit=None):
@@ -136,56 +180,71 @@ def parse_int(value, base_unit=None):
True True
>>> parse_int('1000 ms', 's') == 1 >>> parse_int('1000 ms', 's') == 1
True True
>>> parse_int('1GB', 'MB') is None >>> parse_int('1TB', 'GB') is None
True True
>>> parse_int(0) == 0 >>> parse_int(0) == 0
True True
>>> parse_int('6GB', '16MB') == 384
True
>>> parse_int('4097.4kB', 'kB') == 4097
True
>>> parse_int('4097.5kB', 'kB') == 4098
True
""" """
convert = { val, unit = strtol(value)
'kB': {'kB': 1, 'MB': 1024, 'GB': 1024 * 1024, 'TB': 1024 * 1024 * 1024}, if val is None and unit.startswith('.') or unit and unit[0] in ('.', 'e', 'E'):
'ms': {'ms': 1, 's': 1000, 'min': 1000 * 60, 'h': 1000 * 60 * 60, 'd': 1000 * 60 * 60 * 24}, val, unit = strtod(value)
's': {'ms': -1000, 's': 1, 'min': 60, 'h': 60 * 60, 'd': 60 * 60 * 24},
'min': {'ms': -1000 * 60, 's': -60, 'min': 1, 'h': 60, 'd': 60 * 24}
}
value, unit = strtol(value) if val is not None:
if value is not None: unit = unit.strip()
if not unit: if not unit:
return value return int(rint(val))
if base_unit and base_unit not in convert: val = convert_to_base_unit(val, unit, base_unit)
base_value, base_unit = strtol(base_unit, False) if val is not None:
else: return int(rint(val))
base_value = 1
if base_unit in convert and unit in convert[base_unit]:
multiplier = convert[base_unit][unit] def parse_real(value, base_unit=None):
if multiplier < 0: """
value /= -multiplier >>> parse_real(' +0.0005 ') == 0.0005
else: True
value *= multiplier >>> parse_real('0.0005ms', 'ms') == 0.0
return int(value/base_value) True
>>> parse_real('0.00051ms', 'ms') == 0.001
True
"""
val, unit = strtod(value)
if val is not None:
unit = unit.strip()
if not unit:
return val
return convert_to_base_unit(val, unit, base_unit)
def compare_values(vartype, unit, old_value, new_value): def compare_values(vartype, unit, old_value, new_value):
""" """
>>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE') >>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE')
True True
>>> compare_values('real', None, '1.23', 1.23) >>> compare_values('real', None, '1e-06', 0.000001)
True True
""" """
# if the integer or bool new_value is not correct this function will return False converters = {
if vartype == 'bool': 'bool': lambda v1, v2: parse_bool(v1),
old_value = parse_bool(old_value) 'integer': parse_int,
new_value = parse_bool(new_value) 'real': parse_real,
elif vartype == 'integer': 'enum': lambda v1, v2: str(v1).lower(),
old_value = parse_int(old_value) 'string': lambda v1, v2: str(v1)
new_value = parse_int(new_value, unit) }
elif vartype == 'enum':
return str(old_value).lower() == str(new_value).lower() convert = converters.get(vartype) or converters['string']
else: # ('string', 'real') old_value = convert(old_value, None)
return str(old_value) == str(new_value) new_value = convert(new_value, unit)
return old_value is not None and new_value is not None and old_value == new_value return old_value is not None and new_value is not None and old_value == new_value
@@ -252,17 +311,19 @@ class Retry(object):
if self.deadline is not None and self._cur_stoptime is None: if self.deadline is not None and self._cur_stoptime is None:
self._cur_stoptime = time.time() + self.deadline self._cur_stoptime = time.time() + self.deadline
return func(*args, **kwargs) return func(*args, **kwargs)
except self.retry_exceptions: except self.retry_exceptions as e:
# Note: max_tries == -1 means infinite tries. # Note: max_tries == -1 means infinite tries.
if self._attempts == self.max_tries: if self._attempts == self.max_tries:
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._cur_delay + (random.randint(0, self.max_jitter) / 100.0) sleeptime = self._cur_delay + (random.randint(0, self.max_jitter) / 100.0)
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)
raise RetryFailedError("Exceeded retry deadline") raise RetryFailedError("Exceeded retry deadline")
else: logger.debug('Retry got exception: %s', e)
self.sleep_func(sleeptime) self.sleep_func(sleeptime)
self._cur_delay = min(self._cur_delay * self.backoff, self.max_delay) self._cur_delay = min(self._cur_delay * self.backoff, self.max_delay)
@@ -281,3 +342,13 @@ def split_host_port(value, default_port):
t = value.rsplit(':', 1) t = value.rsplit(':', 1)
t.append(default_port) t.append(default_port)
return t[0], int(t[1]) return t[0], int(t[1])
def uri(proto, netloc, path='', user=None):
host, port = netloc if isinstance(netloc, (list, tuple)) else split_host_port(netloc, 0)
if host and ':' in host and host[0] != '[' and host[-1] != ']':
host = '[{0}]'.format(host)
port = ':{0}'.format(port) if port else ''
path = '/{0}'.format(path) if path and not path.startswith('/') else path
user = '{0}@'.format(user) if user else ''
return '{0}://{1}{2}{3}{4}'.format(proto, user, host, port, path)
+1 -1
View File
@@ -1 +1 @@
__version__ = '1.4.2' __version__ = '1.6.0'
+3 -2
View File
@@ -1,6 +1,5 @@
import collections import collections
import ctypes import ctypes
import fcntl
import os import os
import platform import platform
from patroni.watchdog.base import WatchdogBase, WatchdogError from patroni.watchdog.base import WatchdogBase, WatchdogError
@@ -162,7 +161,9 @@ class LinuxWatchdogDevice(WatchdogBase):
Raises OSError or IOError (Python 2) when the ioctl fails.""" Raises OSError or IOError (Python 2) when the ioctl fails."""
if self._fd is None: if self._fd is None:
raise WatchdogError("Watchdog device is closed") raise WatchdogError("Watchdog device is closed")
fcntl.ioctl(self._fd, func, arg, True) if os.name != 'nt':
import fcntl
fcntl.ioctl(self._fd, func, arg, True)
def get_support(self): def get_support(self):
if self._support_cache is None: if self._support_cache is None:
+22 -2
View File
@@ -11,6 +11,11 @@ restapi:
# username: username # username: username
# password: password # password: password
# ctl:
# insecure: false # Allow connections to SSL sites without certs
# certfile: /etc/ssl/certs/ssl-cert-snakeoil.pem
# cacert: /etc/ssl/certs/ssl-cacert-snakeoil.pem
etcd: etcd:
host: 127.0.0.1:2379 host: 127.0.0.1:2379
@@ -24,6 +29,10 @@ bootstrap:
maximum_lag_on_failover: 1048576 maximum_lag_on_failover: 1048576
# master_start_timeout: 300 # master_start_timeout: 300
# synchronous_mode: false # synchronous_mode: false
#standby_cluster:
#host: 127.0.0.1
#port: 1111
#primary_slot_name: patroni
postgresql: postgresql:
use_pg_rewind: true use_pg_rewind: true
# use_slots: true # use_slots: true
@@ -31,8 +40,8 @@ bootstrap:
# wal_level: hot_standby # wal_level: hot_standby
# hot_standby: "on" # hot_standby: "on"
# wal_keep_segments: 8 # wal_keep_segments: 8
# max_wal_senders: 5 # max_wal_senders: 10
# max_replication_slots: 5 # max_replication_slots: 10
# wal_log_hints: "on" # wal_log_hints: "on"
# archive_mode: "on" # archive_mode: "on"
# archive_timeout: 1800s # archive_timeout: 1800s
@@ -46,6 +55,9 @@ bootstrap:
- data-checksums - data-checksums
pg_hba: # Add following lines to pg_hba.conf after running 'initdb' pg_hba: # Add following lines to pg_hba.conf after running 'initdb'
# For kerberos gss based connectivity (discard @.*$)
#- host replication replicator 127.0.0.1/32 gss include_realm=0
#- host all all 0.0.0.0/0 gss include_realm=0
- host replication replicator 127.0.0.1/32 md5 - host replication replicator 127.0.0.1/32 md5
- host all all 0.0.0.0/0 md5 - host all all 0.0.0.0/0 md5
# - hostssl all all 0.0.0.0/0 md5 # - hostssl all all 0.0.0.0/0 md5
@@ -75,7 +87,15 @@ postgresql:
superuser: superuser:
username: postgres username: postgres
password: zalando password: zalando
rewind: # Has no effect on postgres 10 and lower
username: rewind_user
password: rewind_password
# Server side kerberos spn
# krbsrvname: postgres
parameters: parameters:
# Fully qualified kerberos ticket file for the running user
# same as KRB5CCNAME used by the GSS
# krb_server_keyfile: /var/spool/keytabs/postgres
unix_socket_directories: '.' unix_socket_directories: '.'
#watchdog: #watchdog:
+21 -2
View File
@@ -11,6 +11,11 @@ restapi:
# username: username # username: username
# password: password # password: password
# ctl:
# insecure: false # Allow connections to SSL sites without certs
# certfile: /etc/ssl/certs/ssl-cert-snakeoil.pem
# cacert: /etc/ssl/certs/ssl-cacert-snakeoil.pem
etcd: etcd:
host: 127.0.0.1:2379 host: 127.0.0.1:2379
@@ -29,8 +34,8 @@ bootstrap:
# wal_level: hot_standby # wal_level: hot_standby
# hot_standby: "on" # hot_standby: "on"
# wal_keep_segments: 8 # wal_keep_segments: 8
# max_wal_senders: 5 # max_wal_senders: 10
# max_replication_slots: 5 # max_replication_slots: 10
# wal_log_hints: "on" # wal_log_hints: "on"
# archive_mode: "on" # archive_mode: "on"
# archive_timeout: 1800s # archive_timeout: 1800s
@@ -44,6 +49,9 @@ bootstrap:
- data-checksums - data-checksums
pg_hba: # Add following lines to pg_hba.conf after running 'initdb' pg_hba: # Add following lines to pg_hba.conf after running 'initdb'
# For kerberos gss based connectivity (discard @.*$)
#- host replication replicator 127.0.0.1/32 gss include_realm=0
#- host all all 0.0.0.0/0 gss include_realm=0
- host replication replicator 127.0.0.1/32 md5 - host replication replicator 127.0.0.1/32 md5
- host all all 0.0.0.0/0 md5 - host all all 0.0.0.0/0 md5
# - hostssl all all 0.0.0.0/0 md5 # - hostssl all all 0.0.0.0/0 md5
@@ -73,8 +81,19 @@ postgresql:
superuser: superuser:
username: postgres username: postgres
password: zalando password: zalando
rewind: # Has no effect on postgres 10 and lower
username: rewind_user
password: rewind_password
# Server side kerberos spn
# krbsrvname: postgres
parameters: parameters:
# Fully qualified kerberos ticket file for the running user
# same as KRB5CCNAME used by the GSS
# krb_server_keyfile: /var/spool/keytabs/postgres
unix_socket_directories: '.' unix_socket_directories: '.'
basebackup:
- verbose
- max-rate: 100M
tags: tags:
nofailover: false nofailover: false
noloadbalance: false noloadbalance: false
+18 -2
View File
@@ -11,6 +11,11 @@ restapi:
username: username username: username
password: password password: password
# ctl:
# insecure: false # Allow connections to SSL sites without certs
# certfile: /etc/ssl/certs/ssl-cert-snakeoil.pem
# cacert: /etc/ssl/certs/ssl-cacert-snakeoil.pem
etcd: etcd:
host: 127.0.0.1:2379 host: 127.0.0.1:2379
@@ -29,8 +34,8 @@ bootstrap:
# wal_level: hot_standby # wal_level: hot_standby
# hot_standby: "on" # hot_standby: "on"
# wal_keep_segments: 8 # wal_keep_segments: 8
# max_wal_senders: 5 # max_wal_senders: 10
# max_replication_slots: 5 # max_replication_slots: 10
# wal_log_hints: "on" # wal_log_hints: "on"
# archive_mode: "on" # archive_mode: "on"
# archive_timeout: 1800s # archive_timeout: 1800s
@@ -44,6 +49,9 @@ bootstrap:
- data-checksums - data-checksums
pg_hba: # Add following lines to pg_hba.conf after running 'initdb' pg_hba: # Add following lines to pg_hba.conf after running 'initdb'
# For kerberos gss based connectivity (discard @.*$)
#- host replication replicator 127.0.0.1/32 gss include_realm=0
#- host all all 0.0.0.0/0 gss include_realm=0
- host replication replicator 127.0.0.1/32 md5 - host replication replicator 127.0.0.1/32 md5
- host all all 0.0.0.0/0 md5 - host all all 0.0.0.0/0 md5
# - hostssl all all 0.0.0.0/0 md5 # - hostssl all all 0.0.0.0/0 md5
@@ -70,7 +78,15 @@ postgresql:
superuser: superuser:
username: postgres username: postgres
password: zalando password: zalando
rewind: # Has no effect on postgres 10 and lower
username: rewind_user
password: rewind_password
# Server side kerberos spn
# krbsrvname: postgres
parameters: parameters:
# Fully qualified kerberos ticket file for the running user
# same as KRB5CCNAME used by the GSS
# krb_server_keyfile: /var/spool/keytabs/postgres
unix_socket_directories: '.' unix_socket_directories: '.'
tags: tags:
nofailover: false nofailover: false
+2 -3
View File
@@ -1,6 +1,5 @@
urllib3>=1.19.1,!=1.21 urllib3>=1.19.1,!=1.21
boto boto
psycopg2>=2.5.4
PyYAML PyYAML
requests requests
six >= 1.7 six >= 1.7
@@ -11,6 +10,6 @@ click>=4.1
prettytable>=0.7 prettytable>=0.7
tzlocal tzlocal
python-dateutil python-dateutil
psutil psutil>=2.0.0
cdiff cdiff
kubernetes==3.0.0 kubernetes>=2.0.0,<=7.0.0,!=4.0.*,!=5.0.*
+26 -26
View File
@@ -8,33 +8,29 @@ import inspect
import os import os
import sys import sys
from patroni import check_psycopg2, fatal
from patroni.version import __version__ as VERSION
from setuptools.command.test import test as TestCommand from setuptools.command.test import test as TestCommand
from setuptools import find_packages, setup from setuptools import find_packages, setup
if sys.version_info < (2, 7, 0): if sys.version_info < (2, 7, 0):
sys.stderr.write('FATAL: patroni needs to be run with Python 2.7+\n') fatal('patroni needs to be run with Python 2.7+')
sys.exit(1) check_psycopg2()
del sys.modules['patroni']
del sys.modules['patroni.version']
__location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe()))) __location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())))
def read_version(package):
data = {}
with open(os.path.join(package, 'version.py'), 'r') as fd:
exec(fd.read(), data)
return data['__version__']
NAME = 'patroni' NAME = 'patroni'
MAIN_PACKAGE = NAME MAIN_PACKAGE = NAME
SCRIPTS = 'scripts' SCRIPTS = 'scripts'
VERSION = read_version(MAIN_PACKAGE)
DESCRIPTION = 'PostgreSQL High-Available orchestrator and CLI' DESCRIPTION = 'PostgreSQL High-Available orchestrator and CLI'
LICENSE = 'The MIT License' LICENSE = 'The MIT License'
URL = 'https://github.com/zalando/patroni' URL = 'https://github.com/zalando/patroni'
AUTHOR = 'Alexander Kukushkin, Oleksii Kliukin, Feike Steenbergen' AUTHOR = 'Alexander Kukushkin, Dmitrii Dolgov, Oleksii Kliukin'
AUTHOR_EMAIL = '[email protected], [email protected], [email protected]' AUTHOR_EMAIL = '[email protected], [email protected], [email protected]'
KEYWORDS = 'etcd governor patroni postgresql postgres ha haproxy confd zookeeper exhibitor consul streaming replication' KEYWORDS = 'etcd governor patroni postgresql postgres ha haproxy confd' +\
' zookeeper exhibitor consul streaming replication kubernetes k8s'
COVERAGE_XML = True COVERAGE_XML = True
COVERAGE_HTML = False COVERAGE_HTML = False
@@ -43,16 +39,22 @@ JUNIT_XML = True
# Add here all kinds of additional classifiers as defined under # Add here all kinds of additional classifiers as defined under
# https://pypi.python.org/pypi?%3Aaction=list_classifiers # https://pypi.python.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [ CLASSIFIERS = [
'Development Status :: 4 - Beta', 'Development Status :: 5 - Production/Stable',
'Environment :: Console', 'Environment :: Console',
'Intended Audience :: Developers', 'Intended Audience :: Developers',
'Intended Audience :: System Administrators', 'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License', 'License :: OSI Approved :: MIT License',
'Operating System :: MacOS',
'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Linux',
'Operating System :: POSIX :: BSD :: FreeBSD',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python', 'Programming Language :: Python',
'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: CPython',
] ]
@@ -100,31 +102,29 @@ class PyTest(TestCommand):
silence = logging.WARNING silence = logging.WARNING
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=os.getenv('LOGLEVEL', silence)) logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=os.getenv('LOGLEVEL', silence))
params['args'] += ['-s' if logging.getLogger().getEffectiveLevel() < silence else '--capture=fd'] params['args'] += ['-s' if logging.getLogger().getEffectiveLevel() < silence else '--capture=fd']
if not os.getenv('SYSTEMROOT'):
os.environ['SYSTEMROOT'] = '/'
errno = pytest.main(**params) errno = pytest.main(**params)
sys.exit(errno) sys.exit(errno)
def get_install_requirements(path):
content = open(os.path.join(__location__, path)).read()
return [req for req in content.split('\n') if req != '']
def read(fname): def read(fname):
return open(os.path.join(__location__, fname)).read() with open(os.path.join(__location__, fname)) as fd:
return fd.read()
def setup_package(): def setup_package():
# Assemble additional setup commands # Assemble additional setup commands
cmdclass = {'test': PyTest} cmdclass = {'test': PyTest}
# Some helper variables
version = os.getenv('GO_PIPELINE_LABEL', VERSION)
install_requires = [] install_requires = []
extras_require = {'aws': ['boto'], 'etcd': ['python-etcd'], 'consul': ['python-consul'], extras_require = {'aws': ['boto'], 'etcd': ['python-etcd'], 'consul': ['python-consul'],
'exhibitor': ['kazoo'], 'zookeeper': ['kazoo'], 'kubernetes': ['kubernetes']} 'exhibitor': ['kazoo'], 'zookeeper': ['kazoo'], 'kubernetes': ['kubernetes']}
for r in get_install_requirements('requirements.txt'): for r in read('requirements.txt').split('\n'):
r = r.strip()
if r == '':
continue
extra = False extra = False
for e, v in extras_require.items(): for e, v in extras_require.items():
if r.startswith(v[0]): if r.startswith(v[0]):
@@ -143,7 +143,7 @@ def setup_package():
setup( setup(
name=NAME, name=NAME,
version=version, version=VERSION,
url=URL, url=URL,
author=AUTHOR, author=AUTHOR,
author_email=AUTHOR_EMAIL, author_email=AUTHOR_EMAIL,
+216
View File
@@ -0,0 +1,216 @@
import datetime
import json
import os
import shutil
import unittest
from mock import Mock, patch
from tempfile import gettempdir
import psycopg2
import requests
from patroni.dcs import Leader, Member
from patroni.postgresql import Postgresql
from patroni.postgresql.config import ConfigHandler
from patroni.utils import RetryFailedError
class SleepException(Exception):
pass
class MockResponse(object):
def __init__(self, status_code=200):
self.status_code = status_code
self.content = '{}'
self.ok = True
def json(self):
return json.loads(self.content)
@property
def data(self):
return self.content.encode('utf-8')
@property
def text(self):
return self.content
@property
def status(self):
return self.status_code
@staticmethod
def getheader(*args):
return ''
def requests_get(url, **kwargs):
members = '[{"id":14855829450254237642,"peerURLs":["http://localhost:2380","http://localhost:7001"],' +\
'"name":"default","clientURLs":["http://localhost:2379","http://localhost:4001"]}]'
response = MockResponse()
if url.startswith('http://local'):
raise requests.exceptions.RequestException()
elif ':8011/patroni' in url:
response.content = '{"role": "replica", "xlog": {"received_location": 0}, "tags": {}}'
elif url.endswith('/members'):
response.content = '[{}]' if url.startswith('http://error') else members
elif url.startswith('http://exhibitor'):
response.content = '{"servers":["127.0.0.1","127.0.0.2","127.0.0.3"],"port":2181}'
elif url.endswith(':8011/reinitialize'):
data = kwargs.get('data', '')
if ' false}' in data:
response.status_code = 503
response.ok = False
response.content = 'restarting after failure already in progress'
else:
response.status_code = 404
response.ok = False
return response
class MockPostmaster(object):
def __init__(self, is_running=True, is_single_master=False):
self.is_running = Mock(return_value=is_running)
self.is_single_master = Mock(return_value=is_single_master)
self.wait_for_user_backends_to_close = Mock()
self.signal_stop = Mock(return_value=None)
self.wait = Mock()
class MockCursor(object):
def __init__(self, connection):
self.connection = connection
self.closed = False
self.rowcount = 0
self.results = []
def execute(self, sql, *params):
if sql.startswith('blabla'):
raise psycopg2.ProgrammingError()
elif sql == 'CHECKPOINT' or sql.startswith('SELECT pg_catalog.pg_create_'):
raise psycopg2.OperationalError()
elif sql.startswith('RetryFailedError'):
raise RetryFailedError('retry')
elif sql.startswith('SELECT slot_name'):
self.results = [('blabla', 'physical'), ('foobar', 'physical'), ('ls', 'logical', 'a', 'b')]
elif sql.startswith('SELECT CASE WHEN pg_catalog.pg_is_in_recovery()'):
self.results = [(1, 2)]
elif sql.startswith('SELECT pg_catalog.pg_is_in_recovery()'):
self.results = [(False, 2)]
elif sql.startswith('WITH replication_info AS ('):
replication_info = '[{"application_name":"walreceiver","client_addr":"1.2.3.4",' +\
'"state":"streaming","sync_state":"async","sync_priority":0}]'
self.results = [('', 0, '', '', '', '', False, replication_info)]
elif sql.startswith('SELECT name, setting'):
self.results = [('wal_segment_size', '2048', '8kB', 'integer', 'internal'),
('search_path', 'public', None, 'string', 'user'),
('port', '5433', None, 'integer', 'postmaster'),
('listen_addresses', '*', None, 'string', 'postmaster'),
('autovacuum', 'on', None, 'bool', 'sighup'),
('unix_socket_directories', '/tmp', None, 'string', 'postmaster')]
elif sql.startswith('IDENTIFY_SYSTEM'):
self.results = [('1', 2, '0/402EEC0', '')]
elif sql.startswith('SELECT isdir, modification'):
self.results = [(False, datetime.datetime.now())]
elif sql.startswith('SELECT pg_catalog.pg_read_file'):
self.results = [('1\t0/40159C0\tno recovery target specified\n\n'
'2\t1/40159C0\tno recovery target specified\n',)]
elif sql.startswith('TIMELINE_HISTORY '):
self.results = [('', b'x\t0/40159C0\tno recovery target specified\n\n'
b'1\t0/40159C0\tno recovery target specified\n\n'
b'2\t0/402DD98\tno recovery target specified\n\n'
b'3\t0/403DD98\tno recovery target specified\n')]
else:
self.results = [(None, None, None, None, None, None, None, None, None, None)]
def fetchone(self):
return self.results[0]
def fetchall(self):
return self.results
def __iter__(self):
for i in self.results:
yield i
def __enter__(self):
return self
def __exit__(self, *args):
pass
class MockConnect(object):
server_version = 99999
autocommit = False
closed = 0
def cursor(self):
return MockCursor(self)
def __enter__(self):
return self
def __exit__(self, *args):
pass
@staticmethod
def close():
pass
def psycopg2_connect(*args, **kwargs):
return MockConnect()
class PostgresInit(unittest.TestCase):
_PARAMETERS = {'wal_level': 'hot_standby', 'max_replication_slots': 5, 'f.oo': 'bar',
'search_path': 'public', 'hot_standby': 'on', 'max_wal_senders': 5,
'wal_keep_segments': 8, 'wal_log_hints': 'on', 'max_locks_per_transaction': 64,
'max_worker_processes': 8, 'max_connections': 100, 'max_prepared_transactions': 0,
'track_commit_timestamp': 'off', 'unix_socket_directories': '/tmp', 'trigger_file': 'bla'}
@patch('psycopg2.connect', psycopg2_connect)
@patch.object(ConfigHandler, 'write_postgresql_conf', Mock())
@patch.object(ConfigHandler, 'replace_pg_hba', Mock())
@patch.object(ConfigHandler, 'replace_pg_ident', Mock())
def setUp(self):
data_dir = 'data/test0'
self.p = Postgresql({'name': 'postgresql0', 'scope': 'batman', 'data_dir': data_dir,
'config_dir': data_dir, 'retry_timeout': 10,
'krbsrvname': 'postgres', 'pgpass': os.path.join(gettempdir(), 'pgpass0'),
'listen': '127.0.0.2, 127.0.0.3:5432', 'connect_address': '127.0.0.2:5432',
'authentication': {'superuser': {'username': 'foo', 'password': 'test'},
'replication': {'username': '', 'password': 'rep-pass'}},
'remove_data_directory_on_rewind_failure': True,
'use_pg_rewind': True, 'pg_ctl_timeout': 'bla',
'parameters': self._PARAMETERS,
'recovery_conf': {'foo': 'bar'},
'pg_hba': ['host all all 0.0.0.0/0 md5'],
'pg_ident': ['krb realm postgres'],
'callbacks': {'on_start': 'true', 'on_stop': 'true', 'on_reload': 'true',
'on_restart': 'true', 'on_role_change': 'true'}})
class BaseTestPostgresql(PostgresInit):
def setUp(self):
super(BaseTestPostgresql, self).setUp()
if not os.path.exists(self.p.data_dir):
os.makedirs(self.p.data_dir)
self.leadermem = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres'})
self.leader = Leader(-1, 28, self.leadermem)
self.other = Member(0, 'test-1', 28, {'conn_url': 'postgres://replicator:[email protected]:5433/postgres',
'tags': {'replicatefrom': 'leader'}})
self.me = Member(0, 'test0', 28, {'conn_url': 'postgres://replicator:[email protected]:5434/postgres'})
def tearDown(self):
if os.path.exists(self.p.data_dir):
shutil.rmtree(self.p.data_dir)
+53 -10
View File
@@ -2,6 +2,7 @@ import datetime
import json import json
import psycopg2 import psycopg2
import unittest import unittest
import socket
from mock import Mock, PropertyMock, patch from mock import Mock, PropertyMock, patch
from patroni.api import RestApiHandler, RestApiServer from patroni.api import RestApiHandler, RestApiServer
@@ -10,7 +11,7 @@ from patroni.ha import _MemberStatus
from patroni.utils import tzutc from patroni.utils import tzutc
from six import BytesIO as IO from six import BytesIO as IO
from six.moves import BaseHTTPServer from six.moves import BaseHTTPServer
from test_postgresql import psycopg2_connect, MockCursor from . import psycopg2_connect, MockCursor
future_restart_time = datetime.datetime.now(tzutc) + datetime.timedelta(days=5) future_restart_time = datetime.datetime.now(tzutc) + datetime.timedelta(days=5)
@@ -51,12 +52,16 @@ class MockHa(object):
state_handler = MockPostgresql() state_handler = MockPostgresql()
watchdog = MockWatchdog() watchdog = MockWatchdog()
@staticmethod
def is_leader():
return False
@staticmethod @staticmethod
def reinitialize(_): def reinitialize(_):
return 'reinitialize' return 'reinitialize'
@staticmethod @staticmethod
def restart(): def restart(*args, **kwargs):
return (True, '') return (True, '')
@staticmethod @staticmethod
@@ -69,7 +74,7 @@ class MockHa(object):
@staticmethod @staticmethod
def fetch_nodes_statuses(members): def fetch_nodes_statuses(members):
return [_MemberStatus(None, True, None, None, {}, False)] return [_MemberStatus(None, True, None, 0, None, {}, False)]
@staticmethod @staticmethod
def schedule_future_restart(data): def schedule_future_restart(data):
@@ -91,6 +96,17 @@ class MockHa(object):
def is_paused(): def is_paused():
return True return True
@staticmethod
def is_standby_cluster():
return False
class MockLogger(object):
NORMAL_LOG_QUEUE_SIZE = 2
queue_size = 3
records_lost = 1
class MockPatroni(object): class MockPatroni(object):
@@ -98,6 +114,7 @@ class MockPatroni(object):
config = Mock() config = Mock()
postgresql = ha.state_handler postgresql = ha.state_handler
dcs = Mock() dcs = Mock()
logger = MockLogger()
tags = {} tags = {}
version = '0.00' version = '0.00'
noloadbalance = PropertyMock(return_value=False) noloadbalance = PropertyMock(return_value=False)
@@ -123,20 +140,19 @@ class MockRequest(object):
class MockRestApiServer(RestApiServer): class MockRestApiServer(RestApiServer):
def __init__(self, Handler, request): def __init__(self, Handler, request, config=None):
self.socket = 0 self.socket = 0
self.serve_forever = Mock() self.serve_forever = Mock()
BaseHTTPServer.HTTPServer.__init__ = Mock()
MockRestApiServer._BaseServer__is_shut_down = Mock() MockRestApiServer._BaseServer__is_shut_down = Mock()
MockRestApiServer._BaseServer__shutdown_request = True MockRestApiServer._BaseServer__shutdown_request = True
config = {'listen': '127.0.0.1:8008', 'auth': 'test:test'} config = config or {'listen': '127.0.0.1:8008', 'auth': 'test:test', 'certfile': 'dumb'}
super(MockRestApiServer, self).__init__(MockPatroni(), config) super(MockRestApiServer, self).__init__(MockPatroni(), config)
config['certfile'] = 'dumb'
self.reload_config(config)
Handler(MockRequest(request), ('0.0.0.0', 8080), self) Handler(MockRequest(request), ('0.0.0.0', 8080), self)
@patch('ssl.wrap_socket', Mock(return_value=0)) @patch('ssl.SSLContext.load_cert_chain', Mock())
@patch('ssl.SSLContext.wrap_socket', Mock(return_value=0))
@patch.object(BaseHTTPServer.HTTPServer, '__init__', Mock())
class TestRestApiHandler(unittest.TestCase): class TestRestApiHandler(unittest.TestCase):
_authorization = '\nAuthorization: Basic dGVzdDp0ZXN0' _authorization = '\nAuthorization: Basic dGVzdDp0ZXN0'
@@ -147,14 +163,17 @@ class TestRestApiHandler(unittest.TestCase):
MockRestApiServer(RestApiHandler, 'GET /replica') MockRestApiServer(RestApiHandler, 'GET /replica')
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'master'})): with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'master'})):
MockRestApiServer(RestApiHandler, 'GET /replica') MockRestApiServer(RestApiHandler, 'GET /replica')
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'state': 'running'})):
MockRestApiServer(RestApiHandler, 'GET /health')
MockRestApiServer(RestApiHandler, 'GET /master') MockRestApiServer(RestApiHandler, 'GET /master')
MockPatroni.dcs.cluster.sync.sync_standby = MockPostgresql.name MockPatroni.dcs.cluster.sync.sync_standby = MockPostgresql.name
MockPatroni.dcs.cluster.is_synchronous_mode = Mock(return_value=True) MockPatroni.dcs.cluster.is_synchronous_mode = Mock(return_value=True)
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})): with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})):
MockRestApiServer(RestApiHandler, 'GET /synchronous') MockRestApiServer(RestApiHandler, 'GET /synchronous')
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})): with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'replica'})):
MockPatroni.dcs.cluster.sync.sync_standby = ''
MockRestApiServer(RestApiHandler, 'GET /asynchronous') MockRestApiServer(RestApiHandler, 'GET /asynchronous')
MockPatroni.dcs.cluster.leader.name = MockPostgresql.name MockPatroni.ha.is_leader = Mock(return_value=True)
MockRestApiServer(RestApiHandler, 'GET /replica') MockRestApiServer(RestApiHandler, 'GET /replica')
MockPatroni.dcs.cluster = None MockPatroni.dcs.cluster = None
with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'master'})): with patch.object(RestApiHandler, 'get_postgresql_status', Mock(return_value={'role': 'master'})):
@@ -164,6 +183,8 @@ class TestRestApiHandler(unittest.TestCase):
self.assertIsNotNone(MockRestApiServer(RestApiHandler, 'GET /master')) self.assertIsNotNone(MockRestApiServer(RestApiHandler, 'GET /master'))
with patch.object(RestApiServer, 'query', Mock(return_value=[('', 1, '', '', '', '', False, '')])): with patch.object(RestApiServer, 'query', Mock(return_value=[('', 1, '', '', '', '', False, '')])):
self.assertIsNotNone(MockRestApiServer(RestApiHandler, 'GET /patroni')) self.assertIsNotNone(MockRestApiServer(RestApiHandler, 'GET /patroni'))
with patch.object(MockHa, 'is_standby_cluster', Mock(return_value=True)):
MockRestApiServer(RestApiHandler, 'GET /standby_leader')
def test_do_OPTIONS(self): def test_do_OPTIONS(self):
self.assertIsNotNone(MockRestApiServer(RestApiHandler, 'OPTIONS / HTTP/1.0')) self.assertIsNotNone(MockRestApiServer(RestApiHandler, 'OPTIONS / HTTP/1.0'))
@@ -339,6 +360,7 @@ class TestRestApiHandler(unittest.TestCase):
cluster2 = cluster.copy() cluster2 = cluster.copy()
cluster2.leader.name = 'postgresql0' cluster2.leader.name = 'postgresql0'
cluster2.is_unlocked.return_value = False
dcs.get_cluster.side_effect = [cluster, cluster2] dcs.get_cluster.side_effect = [cluster, cluster2]
MockRestApiServer(RestApiHandler, request) MockRestApiServer(RestApiHandler, request)
@@ -379,3 +401,24 @@ class TestRestApiHandler(unittest.TestCase):
post = 'POST /failover HTTP/1.0' + self._authorization + '\nContent-Length: ' post = 'POST /failover HTTP/1.0' + self._authorization + '\nContent-Length: '
MockRestApiServer(RestApiHandler, post + '14\n\n{"leader":"1"}') MockRestApiServer(RestApiHandler, post + '14\n\n{"leader":"1"}')
MockRestApiServer(RestApiHandler, post + '37\n\n{"candidate":"2","scheduled_at": "1"}') MockRestApiServer(RestApiHandler, post + '37\n\n{"candidate":"2","scheduled_at": "1"}')
@patch('ssl.SSLContext.load_cert_chain', Mock())
@patch('ssl.SSLContext.wrap_socket', Mock(return_value=0))
@patch.object(BaseHTTPServer.HTTPServer, '__init__', Mock())
class TestRestApiServer(unittest.TestCase):
def test_reload_config(self):
bad_config = {'listen': 'foo'}
self.assertRaises(ValueError, MockRestApiServer, None, '', bad_config)
srv = MockRestApiServer(lambda a1, a2, a3: None, '')
self.assertRaises(ValueError, srv.reload_config, bad_config)
self.assertRaises(ValueError, srv.reload_config, {})
with patch.object(socket.socket, 'setsockopt', Mock(side_effect=socket.error)):
srv.reload_config({'listen': ':8008'})
def test_handle_error(self):
try:
raise Exception()
except Exception:
self.assertIsNone(MockRestApiServer.handle_error(None, ('127.0.0.1', 55555)))
+220
View File
@@ -0,0 +1,220 @@
import os
from mock import Mock, PropertyMock, patch
from patroni.async_executor import CriticalTask
from patroni.postgresql import Postgresql
from patroni.postgresql.bootstrap import Bootstrap
from patroni.postgresql.cancellable import CancellableSubprocess
from patroni.postgresql.config import ConfigHandler
from . import psycopg2_connect, BaseTestPostgresql
@patch('subprocess.call', Mock(return_value=0))
@patch('psycopg2.connect', psycopg2_connect)
@patch('os.rename', Mock())
class TestBootstrap(BaseTestPostgresql):
def setUp(self):
super(TestBootstrap, self).setUp()
self.b = self.p.bootstrap
@patch('time.sleep', Mock())
@patch.object(CancellableSubprocess, 'call')
@patch.object(Postgresql, 'remove_data_directory', Mock(return_value=True))
@patch.object(Postgresql, 'data_directory_empty', Mock(return_value=False))
@patch.object(Bootstrap, '_post_restore', Mock(side_effect=OSError))
def test_create_replica(self, mock_cancellable_subprocess_call):
self.p.config._config['create_replica_methods'] = ['pgBackRest']
self.p.config._config['pgBackRest'] = {'command': 'pgBackRest', 'keep_data': True, 'no_params': True}
mock_cancellable_subprocess_call.return_value = 0
self.assertEqual(self.b.create_replica(self.leader), 0)
self.p.config._config['create_replica_methods'] = ['basebackup']
self.p.config._config['basebackup'] = [{'max_rate': '100M'}, 'no-sync']
self.assertEqual(self.b.create_replica(self.leader), 0)
self.p.config._config['basebackup'] = [{'max_rate': '100M', 'compress': '9'}]
with patch('patroni.postgresql.bootstrap.logger.error', new_callable=Mock()) as mock_logger:
self.b.create_replica(self.leader)
mock_logger.assert_called_once()
self.assertTrue("only one key-value is allowed and value should be a string" in mock_logger.call_args[0][0],
"not matching {0}".format(mock_logger.call_args[0][0]))
self.p.config._config['basebackup'] = [42]
with patch('patroni.postgresql.bootstrap.logger.error', new_callable=Mock()) as mock_logger:
self.b.create_replica(self.leader)
mock_logger.assert_called_once()
self.assertTrue("value should be string value or a single key-value pair" in mock_logger.call_args[0][0],
"not matching {0}".format(mock_logger.call_args[0][0]))
self.p.config._config['basebackup'] = {"foo": "bar"}
self.assertEqual(self.b.create_replica(self.leader), 0)
self.p.config._config['create_replica_methods'] = ['wale', 'basebackup']
del self.p.config._config['basebackup']
mock_cancellable_subprocess_call.return_value = 1
self.assertEqual(self.b.create_replica(self.leader), 1)
mock_cancellable_subprocess_call.side_effect = Exception('foo')
self.assertEqual(self.b.create_replica(self.leader), 1)
mock_cancellable_subprocess_call.side_effect = [1, 0]
self.assertEqual(self.b.create_replica(self.leader), 0)
mock_cancellable_subprocess_call.side_effect = [Exception(), 0]
self.assertEqual(self.b.create_replica(self.leader), 0)
self.p.cancellable.cancel()
self.assertEqual(self.b.create_replica(self.leader), 1)
@patch('time.sleep', Mock())
@patch.object(CancellableSubprocess, 'call')
@patch.object(Postgresql, 'remove_data_directory', Mock(return_value=True))
@patch.object(Bootstrap, '_post_restore', Mock(side_effect=OSError))
def test_create_replica_old_format(self, mock_cancellable_subprocess_call):
""" The same test as before but with old 'create_replica_method'
to test backward compatibility
"""
self.p.config._config['create_replica_method'] = ['wale', 'basebackup']
self.p.config._config['wale'] = {'command': 'foo'}
mock_cancellable_subprocess_call.return_value = 0
self.assertEqual(self.b.create_replica(self.leader), 0)
del self.p.config._config['wale']
self.assertEqual(self.b.create_replica(self.leader), 0)
self.p.config._config['create_replica_method'] = ['wale']
mock_cancellable_subprocess_call.return_value = 1
self.assertEqual(self.b.create_replica(self.leader), 1)
def test_basebackup(self):
self.p.cancellable.cancel()
self.b.basebackup(None, None, {'foo': 'bar'})
def test__initdb(self):
self.assertRaises(Exception, self.b.bootstrap, {'initdb': [{'pgdata': 'bar'}]})
self.assertRaises(Exception, self.b.bootstrap, {'initdb': [{'foo': 'bar', 1: 2}]})
self.assertRaises(Exception, self.b.bootstrap, {'initdb': [1]})
self.assertRaises(Exception, self.b.bootstrap, {'initdb': 1})
@patch.object(CancellableSubprocess, 'call', Mock())
@patch.object(Postgresql, 'is_running', Mock(return_value=True))
@patch.object(Postgresql, 'data_directory_empty', Mock(return_value=False))
def test_bootstrap(self):
with patch('subprocess.call', Mock(return_value=1)):
self.assertFalse(self.b.bootstrap({}))
config = {'users': {'replicator': {'password': 'rep-pass', 'options': ['replication']}}}
with patch.object(Postgresql, 'is_running', Mock(return_value=False)),\
patch('multiprocessing.Process', Mock(side_effect=Exception)):
self.assertRaises(Exception, self.b.bootstrap, config)
with open(os.path.join(self.p.data_dir, 'pg_hba.conf')) as f:
lines = f.readlines()
self.assertTrue('host all all 0.0.0.0/0 md5\n' in lines)
self.p.config._config.pop('pg_hba')
config.update({'post_init': '/bin/false',
'pg_hba': ['host replication replicator 127.0.0.1/32 md5',
'hostssl all all 0.0.0.0/0 md5',
'host all all 0.0.0.0/0 md5']})
self.b.bootstrap(config)
with open(os.path.join(self.p.data_dir, 'pg_hba.conf')) as f:
lines = f.readlines()
self.assertTrue('host replication replicator 127.0.0.1/32 md5\n' in lines)
@patch.object(CancellableSubprocess, 'call')
@patch.object(Postgresql, 'get_major_version', Mock(return_value=90600))
def test_custom_bootstrap(self, mock_cancellable_subprocess_call):
self.p.config._config.pop('pg_hba')
config = {'method': 'foo', 'foo': {'command': 'bar'}}
mock_cancellable_subprocess_call.return_value = 1
self.assertFalse(self.b.bootstrap(config))
mock_cancellable_subprocess_call.return_value = 0
with patch('multiprocessing.Process', Mock(side_effect=Exception("42"))),\
patch('os.path.isfile', Mock(return_value=True)),\
patch('os.unlink', Mock()),\
patch.object(ConfigHandler, 'save_configuration_files', Mock()),\
patch.object(ConfigHandler, 'restore_configuration_files', Mock()),\
patch.object(ConfigHandler, 'write_recovery_conf', Mock()):
with self.assertRaises(Exception) as e:
self.b.bootstrap(config)
self.assertEqual(str(e.exception), '42')
config['foo']['recovery_conf'] = {'foo': 'bar'}
with self.assertRaises(Exception) as e:
self.b.bootstrap(config)
self.assertEqual(str(e.exception), '42')
mock_cancellable_subprocess_call.side_effect = Exception
self.assertFalse(self.b.bootstrap(config))
@patch('time.sleep', Mock())
@patch('os.unlink', Mock())
@patch('shutil.copy', Mock())
@patch('os.path.isfile', Mock(return_value=True))
@patch.object(Bootstrap, 'call_post_bootstrap', Mock(return_value=True))
@patch.object(Bootstrap, '_custom_bootstrap', Mock(return_value=True))
@patch.object(Postgresql, 'start', Mock(return_value=True))
@patch.object(Postgresql, 'get_major_version', Mock(return_value=110000))
def test_post_bootstrap(self):
config = {'method': 'foo', 'foo': {'command': 'bar'}}
self.b.bootstrap(config)
task = CriticalTask()
with patch.object(Bootstrap, 'create_or_update_role', Mock(side_effect=Exception)):
self.b.post_bootstrap({}, task)
self.assertFalse(task.result)
self.p.config._config.pop('pg_hba')
self.b.post_bootstrap({}, task)
self.assertTrue(task.result)
self.b.bootstrap(config)
with patch.object(Postgresql, 'pending_restart', PropertyMock(return_value=True)), \
patch.object(Postgresql, 'restart', Mock()) as mock_restart:
self.b.post_bootstrap({}, task)
mock_restart.assert_called_once()
self.b.bootstrap(config)
self.p.set_state('stopped')
self.p.reload_config({'authentication': {'superuser': {'username': 'p', 'password': 'p'},
'replication': {'username': 'r', 'password': 'r'},
'rewind': {'username': 'rw', 'password': 'rw'}},
'listen': '*', 'retry_timeout': 10, 'parameters': {'wal_level': '', 'hba_file': 'foo'}})
with patch.object(Postgresql, 'major_version', PropertyMock(return_value=110000)), \
patch.object(Postgresql, 'restart', Mock()) as mock_restart:
self.b.post_bootstrap({}, task)
mock_restart.assert_called_once()
@patch.object(CancellableSubprocess, 'call')
def test_call_post_bootstrap(self, mock_cancellable_subprocess_call):
mock_cancellable_subprocess_call.return_value = 1
self.assertFalse(self.b.call_post_bootstrap({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.return_value = 0
self.p.config.superuser.pop('username')
self.assertTrue(self.b.call_post_bootstrap({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.assert_called()
args, kwargs = mock_cancellable_subprocess_call.call_args
self.assertTrue('PGPASSFILE' in kwargs['env'])
self.assertEqual(args[0], ['/bin/false', 'postgres://127.0.0.2:5432/postgres'])
mock_cancellable_subprocess_call.reset_mock()
self.p.config._local_address.pop('host')
self.assertTrue(self.b.call_post_bootstrap({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.assert_called()
self.assertEqual(mock_cancellable_subprocess_call.call_args[0][0], ['/bin/false', 'postgres://:5432/postgres'])
mock_cancellable_subprocess_call.side_effect = OSError
self.assertFalse(self.b.call_post_bootstrap({'post_init': '/bin/false'}))
@patch('os.path.exists', Mock(return_value=True))
@patch('os.unlink', Mock())
@patch.object(Bootstrap, 'create_replica', Mock(return_value=0))
def test_clone(self):
self.b.clone(self.leader)
+4 -1
View File
@@ -1,7 +1,7 @@
import unittest import unittest
from mock import Mock, patch from mock import Mock, patch
from patroni.callback_executor import CallbackExecutor from patroni.postgresql.callback_executor import CallbackExecutor
class TestCallbackExecutor(unittest.TestCase): class TestCallbackExecutor(unittest.TestCase):
@@ -17,6 +17,9 @@ class TestCallbackExecutor(unittest.TestCase):
self.assertIsNone(ce.call([])) self.assertIsNone(ce.call([]))
mock_popen.return_value.kill.side_effect = OSError
self.assertIsNone(ce.call([]))
mock_popen.side_effect = Exception mock_popen.side_effect = Exception
ce = CallbackExecutor() ce = CallbackExecutor()
ce._callback_event.wait = Mock(side_effect=[None, Exception]) ce._callback_event.wait = Mock(side_effect=[None, Exception])
+23
View File
@@ -0,0 +1,23 @@
import unittest
from mock import Mock, PropertyMock, patch
from patroni.exceptions import PostgresException
from patroni.postgresql.cancellable import CancellableSubprocess
class TestCancellableSubprocess(unittest.TestCase):
def setUp(self):
self.c = CancellableSubprocess()
def test_call(self):
self.c.cancel()
self.assertRaises(PostgresException, self.c.call, communicate_input=None)
@patch('patroni.postgresql.cancellable.polling_loop', Mock(return_value=[0, 0]))
def test_cancel(self):
self.c._process = Mock()
self.c._process.returncode = None
self.c.cancel()
type(self.c._process).returncode = PropertyMock(side_effect=[None, -15])
self.c.cancel()
+20 -4
View File
@@ -1,6 +1,6 @@
import os import os
import unittest
import sys import sys
import unittest
from mock import MagicMock, Mock, patch from mock import MagicMock, Mock, patch
from patroni.config import Config from patroni.config import Config
@@ -23,13 +23,15 @@ class TestConfig(unittest.TestCase):
def test_set_dynamic_configuration(self): def test_set_dynamic_configuration(self):
with patch.object(Config, '_build_effective_configuration', Mock(side_effect=Exception)): with patch.object(Config, '_build_effective_configuration', Mock(side_effect=Exception)):
self.assertIsNone(self.config.set_dynamic_configuration({'foo': 'bar'})) self.assertIsNone(self.config.set_dynamic_configuration({'foo': 'bar'}))
self.assertTrue(self.config.set_dynamic_configuration({'synchronous_mode': True})) self.assertTrue(self.config.set_dynamic_configuration({'synchronous_mode': True, 'standby_cluster': {}}))
def test_reload_local_configuration(self): def test_reload_local_configuration(self):
os.environ.update({ os.environ.update({
'PATRONI_NAME': 'postgres0', 'PATRONI_NAME': 'postgres0',
'PATRONI_NAMESPACE': '/patroni/', 'PATRONI_NAMESPACE': '/patroni/',
'PATRONI_SCOPE': 'batman2', 'PATRONI_SCOPE': 'batman2',
'PATRONI_LOGLEVEL': 'ERROR',
'PATRONI_LOG_LOGGERS': 'patroni.postmaster: WARNING, urllib3: DEBUG',
'PATRONI_RESTAPI_USERNAME': 'username', 'PATRONI_RESTAPI_USERNAME': 'username',
'PATRONI_RESTAPI_PASSWORD': 'password', 'PATRONI_RESTAPI_PASSWORD': 'password',
'PATRONI_RESTAPI_LISTEN': '0.0.0.0:8008', 'PATRONI_RESTAPI_LISTEN': '0.0.0.0:8008',
@@ -49,7 +51,8 @@ class TestConfig(unittest.TestCase):
'PATRONI_ETCD_CERT': '/cert', 'PATRONI_ETCD_CERT': '/cert',
'PATRONI_ETCD_KEY': '/key', 'PATRONI_ETCD_KEY': '/key',
'PATRONI_CONSUL_HOST': '127.0.0.1:8500', 'PATRONI_CONSUL_HOST': '127.0.0.1:8500',
'PATRONI_KUBERNETES_LABELS': 'a:b:c', 'PATRONI_CONSUL_REGISTER_SERVICE': 'on',
'PATRONI_KUBERNETES_LABELS': 'a: b: c',
'PATRONI_KUBERNETES_SCOPE_LABEL': 'a', 'PATRONI_KUBERNETES_SCOPE_LABEL': 'a',
'PATRONI_KUBERNETES_PORTS': '[{"name": "postgresql"}]', 'PATRONI_KUBERNETES_PORTS': '[{"name": "postgresql"}]',
'PATRONI_ZOOKEEPER_HOSTS': "'host1:2181','host2:2181'", 'PATRONI_ZOOKEEPER_HOSTS': "'host1:2181','host2:2181'",
@@ -70,12 +73,13 @@ class TestConfig(unittest.TestCase):
self.assertRaises(Exception, config.reload_local_configuration, True) self.assertRaises(Exception, config.reload_local_configuration, True)
self.assertTrue(config.reload_local_configuration(True)) self.assertTrue(config.reload_local_configuration(True))
self.assertTrue(config.reload_local_configuration()) self.assertTrue(config.reload_local_configuration())
self.assertIsNone(config.reload_local_configuration())
@patch('tempfile.mkstemp', Mock(return_value=[3000, 'blabla'])) @patch('tempfile.mkstemp', Mock(return_value=[3000, 'blabla']))
@patch('os.path.exists', Mock(return_value=True)) @patch('os.path.exists', Mock(return_value=True))
@patch('os.remove', Mock(side_effect=IOError)) @patch('os.remove', Mock(side_effect=IOError))
@patch('os.close', Mock(side_effect=IOError)) @patch('os.close', Mock(side_effect=IOError))
@patch('os.rename', Mock(return_value=None)) @patch('shutil.move', Mock(return_value=None))
@patch('json.dump', Mock()) @patch('json.dump', Mock())
def test_save_cache(self): def test_save_cache(self):
self.config.set_dynamic_configuration({'ttl': 30, 'postgresql': {'foo': 'bar'}}) self.config.set_dynamic_configuration({'ttl': 30, 'postgresql': {'foo': 'bar'}})
@@ -83,3 +87,15 @@ class TestConfig(unittest.TestCase):
self.config.save_cache() self.config.save_cache()
with patch('os.fdopen', MagicMock()): with patch('os.fdopen', MagicMock()):
self.config.save_cache() self.config.save_cache()
def test_standby_cluster_parameters(self):
dynamic_configuration = {
'standby_cluster': {
'create_replica_methods': ['wal_e', 'basebackup'],
'host': 'localhost',
'port': 5432
}
}
self.config.set_dynamic_configuration(dynamic_configuration)
for name, value in dynamic_configuration['standby_cluster'].items():
self.assertEqual(self.config['standby_cluster'][name], value)
+40 -16
View File
@@ -4,8 +4,8 @@ import unittest
from consul import ConsulException, NotFound from consul import ConsulException, NotFound
from mock import Mock, patch from mock import Mock, patch
from patroni.dcs.consul import AbstractDCS, Cluster, Consul, ConsulInternalError, \ from patroni.dcs.consul import AbstractDCS, Cluster, Consul, ConsulInternalError, \
ConsulError, HTTPClient, InvalidSessionTTL ConsulError, HTTPClient, InvalidSessionTTL, InvalidSession
from test_etcd import SleepException from . import SleepException
def kv_get(self, key, **kwargs): def kv_get(self, key, **kwargs):
@@ -52,6 +52,8 @@ class TestHTTPClient(unittest.TestCase):
self.assertRaises(ConsulInternalError, self.client.get, Mock(), '') self.assertRaises(ConsulInternalError, self.client.get, Mock(), '')
self.client.http.request.return_value.data = b"Invalid Session TTL '3000000000', must be between [10s=24h0m0s]" self.client.http.request.return_value.data = b"Invalid Session TTL '3000000000', must be between [10s=24h0m0s]"
self.assertRaises(InvalidSessionTTL, self.client.get, Mock(), '') self.assertRaises(InvalidSessionTTL, self.client.get, Mock(), '')
self.client.http.request.return_value.data = b"invalid session '16492f43-c2d6-5307-432f-e32d6f7bcbd0'"
self.assertRaises(InvalidSession, self.client.get, Mock(), '')
def test_unknown_method(self): def test_unknown_method(self):
try: try:
@@ -62,7 +64,7 @@ class TestHTTPClient(unittest.TestCase):
def test_put(self): def test_put(self):
self.client.put(Mock(), '/v1/session/create') self.client.put(Mock(), '/v1/session/create')
self.client.put(Mock(), '/v1/session/create', data='{"foo": "bar"}') self.client.put(Mock(), '/v1/session/create', params=[], data='{"foo": "bar"}')
@patch.object(consul.Consul.KV, 'get', kv_get) @patch.object(consul.Consul.KV, 'get', kv_get)
@@ -74,12 +76,14 @@ class TestConsul(unittest.TestCase):
@patch.object(consul.Consul.KV, 'delete', Mock()) @patch.object(consul.Consul.KV, 'delete', Mock())
def setUp(self): def setUp(self):
Consul({'ttl': 30, 'scope': 't', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10, Consul({'ttl': 30, 'scope': 't', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10,
'verify': 'on', 'key': 'foo', 'cert': 'bar', 'cacert': 'buz', 'token': 'asd', 'dc': 'dc1'}) 'verify': 'on', 'key': 'foo', 'cert': 'bar', 'cacert': 'buz', 'token': 'asd', 'dc': 'dc1',
Consul({'ttl': 30, 'scope': 't', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10, 'register_service': True})
'verify': 'on', 'cert': 'bar', 'cacert': 'buz'}) Consul({'ttl': 30, 'scope': 't_', 'name': 'p', 'url': 'https://l:1', 'retry_timeout': 10,
self.c = Consul({'ttl': 30, 'scope': 'test', 'name': 'postgresql1', 'host': 'localhost:1', 'retry_timeout': 10}) 'verify': 'on', 'cert': 'bar', 'cacert': 'buz', 'register_service': True})
self.c = Consul({'ttl': 30, 'scope': 'test', 'name': 'postgresql1', 'host': 'localhost:1', 'retry_timeout': 10,
'register_service': True})
self.c._base_path = '/service/good' self.c._base_path = '/service/good'
self.c._load_cluster() self.c.get_cluster()
@patch('time.sleep', Mock(side_effect=SleepException)) @patch('time.sleep', Mock(side_effect=SleepException))
@patch.object(consul.Consul.Session, 'create', Mock(side_effect=ConsulException)) @patch.object(consul.Consul.Session, 'create', Mock(side_effect=ConsulException))
@@ -108,17 +112,18 @@ class TestConsul(unittest.TestCase):
self.c._session = 'fd4f44fe-2cac-bba5-a60b-304b51ff39b8' self.c._session = 'fd4f44fe-2cac-bba5-a60b-304b51ff39b8'
self.assertIsInstance(self.c.get_cluster(), Cluster) self.assertIsInstance(self.c.get_cluster(), Cluster)
@patch.object(consul.Consul.KV, 'delete', Mock(side_effect=[ConsulException, True, True])) @patch.object(consul.Consul.KV, 'delete', Mock(side_effect=[ConsulException, True, True, True]))
@patch.object(consul.Consul.KV, 'put', Mock(side_effect=[True, ConsulException])) @patch.object(consul.Consul.KV, 'put', Mock(side_effect=[True, ConsulException, InvalidSession]))
def test_touch_member(self): def test_touch_member(self):
self.c.refresh_session = Mock(return_value=True)
self.c.touch_member({'balbla': 'blabla'})
self.c.touch_member({'balbla': 'blabla'})
self.c.touch_member({'balbla': 'blabla'})
self.c.refresh_session = Mock(return_value=False) self.c.refresh_session = Mock(return_value=False)
self.c.touch_member({'balbla': 'blabla'}) self.c.touch_member({'conn_url': 'postgres://replicator:[email protected]:5433/postgres',
'api_url': 'http://127.0.0.1:8009/patroni'})
self.c._register_service = True
self.c.refresh_session = Mock(return_value=True)
for _ in range(0, 4):
self.c.touch_member({'balbla': 'blabla'})
@patch.object(consul.Consul.KV, 'put', Mock(return_value=False)) @patch.object(consul.Consul.KV, 'put', Mock(side_effect=InvalidSession))
def test_take_leader(self): def test_take_leader(self):
self.c.set_ttl(20) self.c.set_ttl(20)
self.c.refresh_session = Mock() self.c.refresh_session = Mock()
@@ -176,3 +181,22 @@ class TestConsul(unittest.TestCase):
@patch.object(consul.Consul.KV, 'put', Mock(return_value=True)) @patch.object(consul.Consul.KV, 'put', Mock(return_value=True))
def test_set_history_value(self): def test_set_history_value(self):
self.assertTrue(self.c.set_history_value('{}')) self.assertTrue(self.c.set_history_value('{}'))
@patch.object(consul.Consul.Agent.Service, 'register', Mock(side_effect=(False, True)))
@patch.object(consul.Consul.Agent.Service, 'deregister', Mock(return_value=True))
def test_update_service(self):
d = {'role': 'replica', 'api_url': 'http://a/t', 'conn_url': 'pg://c:1', 'state': 'running'}
self.assertIsNone(self.c.update_service({}, {}))
self.assertFalse(self.c.update_service({}, d))
self.assertTrue(self.c.update_service(d, d))
self.assertIsNone(self.c.update_service(d, d))
d['state'] = 'stopped'
self.assertTrue(self.c.update_service(d, d, force=True))
d['state'] = 'unknown'
self.assertIsNone(self.c.update_service({}, d))
d['state'] = 'running'
d['role'] = 'bla'
self.assertIsNone(self.c.update_service({}, d))
def test_reload_config(self):
self.c.reload_config({'consul': {'token': 'foo'}, 'loop_wait': 10, 'ttl': 30, 'retry_timeout': 10})
+85 -41
View File
@@ -9,14 +9,15 @@ 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, request_patroni, get_dcs, parse_dcs, \ from patroni.ctl import ctl, store_config, load_config, output_members, request_patroni, 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 format_config_for_editing, show_diff, invoke_editor, format_pg_version, find_executable
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
from test_etcd import etcd_read, requests_get, socket_getaddrinfo, MockResponse
from test_ha import get_cluster_initialized_without_leader, get_cluster_initialized_with_leader, \ from . import MockConnect, MockCursor, MockResponse, psycopg2_connect, requests_get
from .test_etcd import etcd_read, socket_getaddrinfo
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
from test_postgresql import MockConnect, psycopg2_connect
CONFIG_FILE_PATH = './test-ctl.yaml' CONFIG_FILE_PATH = './test-ctl.yaml'
@@ -24,9 +25,9 @@ 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():
store_config({'etcd': {'host': 'localhost:2379'}}, CONFIG_FILE_PATH + '/dummy')
sys.argv = ['patronictl.py', ''] sys.argv = ['patronictl.py', '']
load_config(CONFIG_FILE_PATH + '/dummy', None) load_config(CONFIG_FILE_PATH + '/dummy', None)
store_config({'etcd': {'host': 'localhost:2379'}}, CONFIG_FILE_PATH + '/dummy')
load_config(CONFIG_FILE_PATH + '/dummy', '0.0.0.0') load_config(CONFIG_FILE_PATH + '/dummy', '0.0.0.0')
os.remove(CONFIG_FILE_PATH + '/dummy') os.remove(CONFIG_FILE_PATH + '/dummy')
os.rmdir(CONFIG_FILE_PATH) os.rmdir(CONFIG_FILE_PATH)
@@ -89,10 +90,15 @@ class TestCtl(unittest.TestCase):
result = self.runner.invoke(ctl, ['switchover', 'dummy', '--force', '--scheduled', '2015-01-01T12:00:00']) result = self.runner.invoke(ctl, ['switchover', 'dummy', '--force', '--scheduled', '2015-01-01T12:00:00'])
assert result.exit_code == 1 assert result.exit_code == 1
# Aborting switchover, as we anser NO to the confirmation # Aborting switchover, as we answer NO to the confirmation
result = self.runner.invoke(ctl, ['switchover', 'dummy'], input='leader\nother\n\nN') result = self.runner.invoke(ctl, ['switchover', 'dummy'], input='leader\nother\n\nN')
assert result.exit_code == 1 assert result.exit_code == 1
# Aborting scheduled switchover, as we answer NO to the confirmation
result = self.runner.invoke(ctl, ['switchover', 'dummy', '--scheduled', '2015-01-01T12:00:00+01:00'],
input='leader\nother\n\nN')
assert result.exit_code == 1
# Target and source are equal # Target and source are equal
result = self.runner.invoke(ctl, ['switchover', 'dummy'], input='leader\nleader\n\ny') result = self.runner.invoke(ctl, ['switchover', 'dummy'], input='leader\nleader\n\ny')
assert result.exit_code == 1 assert result.exit_code == 1
@@ -192,24 +198,24 @@ class TestCtl(unittest.TestCase):
def test_query_member(self): def test_query_member(self):
with patch('patroni.ctl.get_cursor', Mock(return_value=MockConnect().cursor())): with patch('patroni.ctl.get_cursor', Mock(return_value=MockConnect().cursor())):
rows = query_member(None, None, None, 'master', 'SELECT 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_is_in_recovery()', {}) rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {})
self.assertEquals(rows, (None, None)) self.assertEqual(rows, (None, None))
with patch('test_postgresql.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_is_in_recovery()', {}) rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {})
with patch('patroni.ctl.get_cursor', Mock(return_value=None)): with patch('patroni.ctl.get_cursor', Mock(return_value=None)):
rows = query_member(None, None, None, None, 'SELECT pg_is_in_recovery()', {}) rows = query_member(None, None, None, None, 'SELECT pg_catalog.pg_is_in_recovery()', {})
self.assertTrue('No connection to' in str(rows)) self.assertTrue('No connection to' in str(rows))
rows = query_member(None, None, None, 'replica', 'SELECT pg_is_in_recovery()', {}) rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {})
self.assertTrue('No connection to' in str(rows)) self.assertTrue('No connection to' in str(rows))
with patch('patroni.ctl.get_cursor', Mock(side_effect=OperationalError('bla'))): with patch('patroni.ctl.get_cursor', Mock(side_effect=OperationalError('bla'))):
rows = query_member(None, None, None, 'replica', 'SELECT pg_is_in_recovery()', {}) rows = query_member(None, None, None, 'replica', 'SELECT pg_catalog.pg_is_in_recovery()', {})
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
def test_dsn(self, mock_get_dcs): def test_dsn(self, mock_get_dcs):
@@ -225,11 +231,27 @@ class TestCtl(unittest.TestCase):
result = self.runner.invoke(ctl, ['dsn', 'alpha', '--member', 'dummy']) result = self.runner.invoke(ctl, ['dsn', 'alpha', '--member', 'dummy'])
assert result.exit_code == 1 assert result.exit_code == 1
@patch('requests.post')
@patch('patroni.ctl.get_dcs')
def test_reload(self, mock_get_dcs, mock_post):
mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader
result = self.runner.invoke(ctl, ['reload', 'alpha'], input='y')
assert 'Failed: reload for member' in result.output
mock_post.return_value.status_code = 200
result = self.runner.invoke(ctl, ['reload', 'alpha'], input='y')
assert 'No changes to apply on member' in result.output
mock_post.return_value.status_code = 202
result = self.runner.invoke(ctl, ['reload', 'alpha'], input='y')
assert 'Reload request received for member' in result.output
@patch('requests.post', requests_get) @patch('requests.post', requests_get)
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
def test_restart_reinit(self, mock_get_dcs): def test_restart_reinit(self, mock_get_dcs):
mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader
result = self.runner.invoke(ctl, ['restart', 'alpha'], input='y\n\nnow') result = self.runner.invoke(ctl, ['restart', 'alpha'], input='now\ny\n')
assert 'Failed: restart for' in result.output assert 'Failed: restart for' in result.output
assert result.exit_code == 0 assert result.exit_code == 0
@@ -241,18 +263,22 @@ class TestCtl(unittest.TestCase):
assert result.exit_code == 0 assert result.exit_code == 0
# Aborted restart # Aborted restart
result = self.runner.invoke(ctl, ['restart', 'alpha'], input='N') result = self.runner.invoke(ctl, ['restart', 'alpha'], input='now\nN')
assert result.exit_code == 1 assert result.exit_code == 1
result = self.runner.invoke(ctl, ['restart', 'alpha', '--pending', '--force']) result = self.runner.invoke(ctl, ['restart', 'alpha', '--pending', '--force'])
assert result.exit_code == 0 assert result.exit_code == 0
# Aborted scheduled restart
result = self.runner.invoke(ctl, ['restart', 'alpha', '--scheduled', '2019-10-01T14:30'], input='N')
assert result.exit_code == 1
# Not a member # Not a member
result = self.runner.invoke(ctl, ['restart', 'alpha', 'dummy', '--any'], input='y') result = self.runner.invoke(ctl, ['restart', 'alpha', 'dummy', '--any'], input='now\ny')
assert result.exit_code == 1 assert result.exit_code == 1
# Wrong pg version # Wrong pg version
result = self.runner.invoke(ctl, ['restart', 'alpha', '--any', '--pg-version', '9.1'], input='y') result = self.runner.invoke(ctl, ['restart', 'alpha', '--any', '--pg-version', '9.1'], input='now\ny')
assert 'Error: Invalid PostgreSQL version format' in result.output assert 'Error: Invalid PostgreSQL version format' in result.output
assert result.exit_code == 1 assert result.exit_code == 1
@@ -273,14 +299,14 @@ class TestCtl(unittest.TestCase):
with patch('requests.post', Mock(return_value=MockResponse())): with patch('requests.post', Mock(return_value=MockResponse())):
# normal restart, the schedule is actually parsed, but not validated in patronictl # normal restart, the schedule is actually parsed, but not validated in patronictl
result = self.runner.invoke(ctl, ['restart', 'alpha', '--pg-version', '42.0.0', result = self.runner.invoke(ctl, ['restart', 'alpha', '--pg-version', '42.0.0',
'--scheduled', '2300-10-01T14:30'], input='y') '--scheduled', '2300-10-01T14:30'], input='y')
assert result.exit_code == 0 assert result.exit_code == 0
with patch('requests.post', Mock(return_value=MockResponse(204))): with patch('requests.post', Mock(return_value=MockResponse(204))):
# get restart with the non-200 return code # get restart with the non-200 return code
# normal restart, the schedule is actually parsed, but not validated in patronictl # normal restart, the schedule is actually parsed, but not validated in patronictl
result = self.runner.invoke(ctl, ['restart', 'alpha', '--pg-version', '42.0', result = self.runner.invoke(ctl, ['restart', 'alpha', '--pg-version', '42.0',
'--scheduled', '2300-10-01T14:30'], input='y') '--scheduled', '2300-10-01T14:30'], input='y')
assert result.exit_code == 0 assert result.exit_code == 0
# force restart with restart already present # force restart with restart already present
@@ -328,8 +354,14 @@ class TestCtl(unittest.TestCase):
assert result.exit_code == 0 assert result.exit_code == 0
@patch('requests.post', Mock(side_effect=requests.exceptions.ConnectionError('foo'))) @patch('requests.post', Mock(side_effect=requests.exceptions.ConnectionError('foo')))
def test_request_patroni(self): @patch('click.get_current_context')
def test_request_patroni(self, mock_context):
member = get_cluster_initialized_with_leader().leader.member member = get_cluster_initialized_with_leader().leader.member
mock_context.return_value.obj = {'ctl': {'cacert': 'cert.pem'}}
self.assertRaises(requests.exceptions.ConnectionError, request_patroni, member, 'post', 'dummy', {})
mock_context.return_value.obj = {'ctl': {'insecure': True}}
self.assertRaises(requests.exceptions.ConnectionError, request_patroni, member, 'post', 'dummy', {}) self.assertRaises(requests.exceptions.ConnectionError, request_patroni, member, 'post', 'dummy', {})
def test_ctl(self): def test_ctl(self):
@@ -342,20 +374,20 @@ class TestCtl(unittest.TestCase):
self.assertIsNone(get_any_member(get_cluster_initialized_without_leader(), role='master')) self.assertIsNone(get_any_member(get_cluster_initialized_without_leader(), role='master'))
m = get_any_member(get_cluster_initialized_with_leader(), role='master') m = get_any_member(get_cluster_initialized_with_leader(), role='master')
self.assertEquals(m.name, 'leader') self.assertEqual(m.name, 'leader')
def test_get_all_members(self): def test_get_all_members(self):
self.assertEquals(list(get_all_members(get_cluster_initialized_without_leader(), role='master')), []) self.assertEqual(list(get_all_members(get_cluster_initialized_without_leader(), role='master')), [])
r = list(get_all_members(get_cluster_initialized_with_leader(), role='master')) r = list(get_all_members(get_cluster_initialized_with_leader(), role='master'))
self.assertEquals(len(r), 1) self.assertEqual(len(r), 1)
self.assertEquals(r[0].name, 'leader') self.assertEqual(r[0].name, 'leader')
r = list(get_all_members(get_cluster_initialized_with_leader(), role='replica')) r = list(get_all_members(get_cluster_initialized_with_leader(), role='replica'))
self.assertEquals(len(r), 1) self.assertEqual(len(r), 1)
self.assertEquals(r[0].name, 'other') self.assertEqual(r[0].name, 'other')
self.assertEquals(len(list(get_all_members(get_cluster_initialized_without_leader(), role='replica'))), 2) self.assertEqual(len(list(get_all_members(get_cluster_initialized_without_leader(), role='replica'))), 2)
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
def test_members(self, mock_get_dcs): def test_members(self, mock_get_dcs):
@@ -477,23 +509,23 @@ class TestCtl(unittest.TestCase):
after_editing, changed_config = apply_config_changes(before_editing, config, after_editing, changed_config = apply_config_changes(before_editing, config,
["postgresql.parameters.work_mem = 5MB", ["postgresql.parameters.work_mem = 5MB",
"ttl=15", "postgresql.use_pg_rewind=off", 'a.b=c']) "ttl=15", "postgresql.use_pg_rewind=off", 'a.b=c'])
self.assertEquals(changed_config, {"a": {"b": "c"}, "postgresql": {"parameters": {"work_mem": "5MB"}, self.assertEqual(changed_config, {"a": {"b": "c"}, "postgresql": {"parameters": {"work_mem": "5MB"},
"use_pg_rewind": False}, "ttl": 15}) "use_pg_rewind": False}, "ttl": 15})
# postgresql.parameters namespace is flattened # postgresql.parameters namespace is flattened
after_editing, changed_config = apply_config_changes(before_editing, config, after_editing, changed_config = apply_config_changes(before_editing, config,
["postgresql.parameters.work_mem.sub = x"]) ["postgresql.parameters.work_mem.sub = x"])
self.assertEquals(changed_config, {"postgresql": {"parameters": {"work_mem": "4MB", "work_mem.sub": "x"}, self.assertEqual(changed_config, {"postgresql": {"parameters": {"work_mem": "4MB", "work_mem.sub": "x"},
"use_pg_rewind": True}, "ttl": 30}) "use_pg_rewind": True}, "ttl": 30})
# Setting to null deletes # Setting to null deletes
after_editing, changed_config = apply_config_changes(before_editing, config, after_editing, changed_config = apply_config_changes(before_editing, config,
["postgresql.parameters.work_mem=null"]) ["postgresql.parameters.work_mem=null"])
self.assertEquals(changed_config, {"postgresql": {"use_pg_rewind": True}, "ttl": 30}) self.assertEqual(changed_config, {"postgresql": {"use_pg_rewind": True}, "ttl": 30})
after_editing, changed_config = apply_config_changes(before_editing, config, after_editing, changed_config = apply_config_changes(before_editing, config,
["postgresql.use_pg_rewind=null", ["postgresql.use_pg_rewind=null",
"postgresql.parameters.work_mem=null"]) "postgresql.parameters.work_mem=null"])
self.assertEquals(changed_config, {"ttl": 30}) self.assertEqual(changed_config, {"ttl": 30})
self.assertRaises(PatroniCtlException, apply_config_changes, before_editing, config, ['a']) self.assertRaises(PatroniCtlException, apply_config_changes, before_editing, config, ['a'])
@@ -511,10 +543,12 @@ class TestCtl(unittest.TestCase):
show_diff(b"foo:\n bar: \xc3\xb6\xc3\xb6\n".decode('utf-8'), show_diff(b"foo:\n bar: \xc3\xb6\xc3\xb6\n".decode('utf-8'),
b"foo:\n bar: \xc3\xbc\xc3\xbc\n".decode('utf-8')) b"foo:\n bar: \xc3\xbc\xc3\xbc\n".decode('utf-8'))
def test_invoke_editor(self): @patch('subprocess.call', return_value=1)
for e in ('', 'false'): def test_invoke_editor(self, mock_subprocess_call):
os.environ['EDITOR'] = e os.environ.pop('EDITOR', None)
self.assertRaises(PatroniCtlException, invoke_editor, 'foo: bar\n', 'test') for e in ('', '/bin/vi'):
with patch('patroni.ctl.find_executable', Mock(return_value=e)):
self.assertRaises(PatroniCtlException, invoke_editor, 'foo: bar\n', 'test')
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
def test_show_config(self, mock_get_dcs): def test_show_config(self, mock_get_dcs):
@@ -526,13 +560,14 @@ class TestCtl(unittest.TestCase):
def test_edit_config(self, mock_get_dcs): def test_edit_config(self, mock_get_dcs):
mock_get_dcs.return_value = self.e mock_get_dcs.return_value = self.e
mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader mock_get_dcs.return_value.get_cluster = get_cluster_initialized_with_leader
mock_get_dcs.return_value.set_config_value = Mock(return_value=False)
os.environ['EDITOR'] = 'true' os.environ['EDITOR'] = 'true'
self.runner.invoke(ctl, ['edit-config', 'dummy']) self.runner.invoke(ctl, ['edit-config', 'dummy'])
self.runner.invoke(ctl, ['edit-config', 'dummy', '-s', 'foo=bar']) self.runner.invoke(ctl, ['edit-config', 'dummy', '-s', 'foo=bar'])
self.runner.invoke(ctl, ['edit-config', 'dummy', '--replace', 'postgres0.yml']) self.runner.invoke(ctl, ['edit-config', 'dummy', '--replace', 'postgres0.yml'])
self.runner.invoke(ctl, ['edit-config', 'dummy', '--apply', '-'], input='foo: bar') self.runner.invoke(ctl, ['edit-config', 'dummy', '--apply', '-'], input='foo: bar')
self.runner.invoke(ctl, ['edit-config', 'dummy', '--force', '--apply', '-'], input='foo: bar') self.runner.invoke(ctl, ['edit-config', 'dummy', '--force', '--apply', '-'], input='foo: bar')
mock_get_dcs.return_value.set_config_value = Mock(return_value=True) mock_get_dcs.return_value.set_config_value.return_value = True
self.runner.invoke(ctl, ['edit-config', 'dummy', '--force', '--apply', '-'], input='foo: bar') self.runner.invoke(ctl, ['edit-config', 'dummy', '--force', '--apply', '-'], input='foo: bar')
@patch('patroni.ctl.get_dcs') @patch('patroni.ctl.get_dcs')
@@ -550,5 +585,14 @@ class TestCtl(unittest.TestCase):
assert 'failed to get version' in result.output assert 'failed to get version' in result.output
def test_format_pg_version(self): def test_format_pg_version(self):
self.assertEquals(format_pg_version(100001), '10.1') self.assertEqual(format_pg_version(100001), '10.1')
self.assertEquals(format_pg_version(90605), '9.6.5') self.assertEqual(format_pg_version(90605), '9.6.5')
@patch('sys.platform', 'win32')
def test_find_executable(self):
with patch('os.path.isfile', Mock(return_value=True)):
self.assertEqual(find_executable('vim'), 'vim.exe')
with patch('os.path.isfile', Mock(return_value=False)):
self.assertIsNone(find_executable('vim'))
with patch('os.path.isfile', Mock(side_effect=[False, True])):
self.assertEqual(find_executable('vim', '/'), '/vim.exe')
+27 -77
View File
@@ -1,7 +1,5 @@
import etcd import etcd
import json
import urllib3.util.connection import urllib3.util.connection
import requests
import socket import socket
import unittest import unittest
@@ -11,56 +9,7 @@ from patroni.dcs.etcd import AbstractDCS, Client, Cluster, Etcd, EtcdError, DnsC
from patroni.exceptions import DCSError from patroni.exceptions import DCSError
from urllib3.exceptions import ReadTimeoutError from urllib3.exceptions import ReadTimeoutError
from . import SleepException, MockResponse, requests_get
class MockResponse(object):
def __init__(self, status_code=200):
self.status_code = status_code
self.content = '{}'
self.ok = True
def json(self):
return json.loads(self.content)
@property
def data(self):
return self.content.encode('utf-8')
@property
def text(self):
return self.content
@property
def status(self):
return self.status_code
@staticmethod
def getheader(*args):
return ''
def requests_get(url, **kwargs):
members = '[{"id":14855829450254237642,"peerURLs":["http://localhost:2380","http://localhost:7001"],' +\
'"name":"default","clientURLs":["http://localhost:2379","http://localhost:4001"]}]'
response = MockResponse()
if url.startswith('http://local'):
raise requests.exceptions.RequestException()
elif ':8011/patroni' in url:
response.content = '{"role": "replica", "xlog": {"received_location": 0}, "tags": {}}'
elif url.endswith('/members'):
response.content = '[{}]' if url.startswith('http://error') else members
elif url.startswith('http://exhibitor'):
response.content = '{"servers":["127.0.0.1","127.0.0.2","127.0.0.3"],"port":2181}'
elif url.endswith(':8011/reinitialize'):
data = kwargs.get('data', '')
if ' false}' in data:
response.status_code = 503
response.ok = False
response.content = 'restarting after failure already in progress'
else:
response.status_code = 404
response.ok = False
return response
def etcd_watch(self, key, index=None, timeout=None, recursive=None): def etcd_watch(self, key, index=None, timeout=None, recursive=None):
@@ -90,7 +39,7 @@ def etcd_read(self, key, **kwargs):
raise etcd.EtcdKeyNotFound raise etcd.EtcdKeyNotFound
response = {"action": "get", "node": {"key": "/service/batman5", "dir": True, "nodes": [ response = {"action": "get", "node": {"key": "/service/batman5", "dir": True, "nodes": [
{"key": "/service/batman5/config", "value": '{"foo": "bar"}', {"key": "/service/batman5/config", "value": '{"synchronous_mode": 0}',
"modifiedIndex": 1582, "createdIndex": 1582}, "modifiedIndex": 1582, "createdIndex": 1582},
{"key": "/service/batman5/failover", "value": "", {"key": "/service/batman5/failover", "value": "",
"modifiedIndex": 1582, "createdIndex": 1582}, "modifiedIndex": 1582, "createdIndex": 1582},
@@ -122,10 +71,6 @@ def etcd_read(self, key, **kwargs):
return result return result
class SleepException(Exception):
pass
def dns_query(name, _): def dns_query(name, _):
if '-server' not in name or '-ssl' in name: if '-server' not in name or '-ssl' in name:
return [] return []
@@ -148,13 +93,14 @@ def socket_getaddrinfo(*args):
def http_request(method, url, **kwargs): def http_request(method, url, **kwargs):
if url == 'http://localhost:2379/timeout': if url == 'http://localhost:2379/timeout':
raise ReadTimeoutError(None, None, None) raise ReadTimeoutError(None, None, None)
ret = MockResponse()
if url == 'http://localhost:2379/v2/machines': if url == 'http://localhost:2379/v2/machines':
ret = MockResponse()
ret.content = 'http://localhost:2379,http://localhost:4001' ret.content = 'http://localhost:2379,http://localhost:4001'
return ret elif url == 'http://localhost:4001/v2/machines':
if url == 'http://localhost:2379/': ret.content = ''
return MockResponse() elif url != 'http://localhost:2379/':
raise socket.error raise socket.error
return ret
class TestDnsCachingResolver(unittest.TestCase): class TestDnsCachingResolver(unittest.TestCase):
@@ -207,15 +153,16 @@ class TestClient(unittest.TestCase):
mock_machines.__get__ = Mock(return_value=['http://localhost:2379']) 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.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.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, '/', '')
self.client._update_machines_cache = True
with patch.object(Client, '_load_machines_cache', Mock(side_effect=etcd.EtcdException)): with patch.object(Client, '_load_machines_cache', Mock(side_effect=etcd.EtcdException)):
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):
self.assertEquals(self.client.get_srv_record('_etcd-server._tcp.blabla'), []) self.assertEqual(self.client.get_srv_record('_etcd-server._tcp.blabla'), [])
self.assertEquals(self.client.get_srv_record('_etcd-server._tcp.exception'), []) self.assertEqual(self.client.get_srv_record('_etcd-server._tcp.exception'), [])
def test__get_machines_cache_from_srv(self): def test__get_machines_cache_from_srv(self):
self.client._get_machines_cache_from_srv('foobar') self.client._get_machines_cache_from_srv('foobar')
@@ -258,24 +205,27 @@ class TestEtcd(unittest.TestCase):
'host': 'localhost:2379', 'scope': 'test', 'name': 'foo'}) 'host': 'localhost:2379', 'scope': 'test', 'name': 'foo'})
def test_base_path(self): def test_base_path(self):
self.assertEquals(self.etcd._base_path, '/patroni/test') self.assertEqual(self.etcd._base_path, '/patroni/test')
@patch('dns.resolver.query', dns_query) @patch('dns.resolver.query', dns_query)
def test_get_etcd_client(self): def test_get_etcd_client(self):
with patch.object(Client, 'machines') as mock_machines: with patch('time.sleep', Mock(side_effect=SleepException)),\
patch.object(Client, 'machines') as mock_machines:
mock_machines.__get__ = Mock(side_effect=etcd.EtcdException) mock_machines.__get__ = Mock(side_effect=etcd.EtcdException)
with patch('time.sleep', Mock(side_effect=SleepException)): self.assertRaises(SleepException, self.etcd.get_etcd_client,
self.assertRaises(SleepException, self.etcd.get_etcd_client, {'discovery_srv': 'test', 'retry_timeout': 10, 'cacert': '1', 'key': '1', 'cert': 1})
{'discovery_srv': 'test', 'retry_timeout': 10, 'cacert': '1', 'key': '1', 'cert': 1}) self.assertRaises(SleepException, self.etcd.get_etcd_client,
self.assertRaises(SleepException, self.etcd.get_etcd_client, {'url': 'https://test:2379', 'retry_timeout': 10})
{'url': 'https://test:2379', 'retry_timeout': 10}) self.assertRaises(SleepException, self.etcd.get_etcd_client,
self.assertRaises(SleepException, self.etcd.get_etcd_client, {'hosts': 'foo:4001,bar', 'retry_timeout': 10})
{'proxy': 'https://user:password@test:2379', 'retry_timeout': 10}) mock_machines.__get__ = Mock(return_value=[])
self.assertRaises(SleepException, self.etcd.get_etcd_client, self.assertRaises(SleepException, self.etcd.get_etcd_client,
{'hosts': 'foo:4001,bar', 'retry_timeout': 10}) {'proxy': 'https://user:password@test:2379', 'retry_timeout': 10})
def test_get_cluster(self): def test_get_cluster(self):
self.assertIsInstance(self.etcd.get_cluster(), Cluster) cluster = self.etcd.get_cluster()
self.assertIsInstance(cluster, Cluster)
self.assertFalse(cluster.is_synchronous_mode())
self.etcd._base_path = '/service/nocluster' self.etcd._base_path = '/service/nocluster'
cluster = self.etcd.get_cluster() cluster = self.etcd.get_cluster()
self.assertIsInstance(cluster, Cluster) self.assertIsInstance(cluster, Cluster)
+3 -2
View File
@@ -3,8 +3,9 @@ import unittest
from mock import Mock, patch from mock import Mock, patch
from patroni.dcs.exhibitor import ExhibitorEnsembleProvider, Exhibitor from patroni.dcs.exhibitor import ExhibitorEnsembleProvider, Exhibitor
from patroni.dcs.zookeeper import ZooKeeperError from patroni.dcs.zookeeper import ZooKeeperError
from test_etcd import SleepException, requests_get
from test_zookeeper import MockKazooClient from . import SleepException, requests_get
from .test_zookeeper import MockKazooClient
@patch('requests.get', requests_get) @patch('requests.get', requests_get)
+304 -150
View File
@@ -1,7 +1,7 @@
import datetime import datetime
import etcd import etcd
import os import os
import unittest import sys
from mock import Mock, MagicMock, PropertyMock, patch from mock import Mock, MagicMock, PropertyMock, patch
from patroni.config import Config from patroni.config import Config
@@ -10,10 +10,18 @@ from patroni.dcs.etcd import Client
from patroni.exceptions import DCSError, PostgresConnectionException, PatroniException from patroni.exceptions import DCSError, PostgresConnectionException, PatroniException
from patroni.ha import Ha, _MemberStatus from patroni.ha import Ha, _MemberStatus
from patroni.postgresql import Postgresql from patroni.postgresql import Postgresql
from patroni.watchdog import Watchdog from patroni.postgresql.bootstrap import Bootstrap
from patroni.postgresql.cancellable import CancellableSubprocess
from patroni.postgresql.config import ConfigHandler
from patroni.postgresql.rewind import Rewind
from patroni.postgresql.slots import SlotsHandler
from patroni.utils import tzutc from patroni.utils import tzutc
from test_etcd import socket_getaddrinfo, etcd_read, etcd_write, requests_get from patroni.watchdog import Watchdog
from test_postgresql import psycopg2_connect, MockPostmaster
from . import PostgresInit, MockPostmaster, psycopg2_connect, requests_get
from .test_etcd import socket_getaddrinfo, etcd_read, etcd_write
SYSID = '12345678901'
def true(*args, **kwargs): def true(*args, **kwargs):
@@ -24,16 +32,19 @@ def false(*args, **kwargs):
return False return False
def get_cluster(initialize, leader, members, failover, sync): def get_cluster(initialize, leader, members, failover, sync, cluster_config=None):
history = TimelineHistory(1, [(1, 67197376, 'no recovery target specified', datetime.datetime.now().isoformat())]) t = datetime.datetime.now().isoformat()
return Cluster(initialize, ClusterConfig(1, {1: 2}, 1), leader, 10, members, failover, sync, history) history = TimelineHistory(1, '[[1,67197376,"no recovery target specified","' + t + '"]]',
[(1, 67197376, 'no recovery target specified', t)])
cluster_config = cluster_config or ClusterConfig(1, {'check_timeline': True}, 1)
return Cluster(initialize, cluster_config, leader, 10, members, failover, sync, history)
def get_cluster_not_initialized_without_leader(): def get_cluster_not_initialized_without_leader(cluster_config=None):
return get_cluster(None, None, [], None, SyncState(None, None, None)) return get_cluster(None, None, [], None, SyncState(None, None, None), cluster_config)
def get_cluster_initialized_without_leader(leader=False, failover=None, sync=None): def get_cluster_initialized_without_leader(leader=False, failover=None, sync=None, cluster_config=None):
m1 = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres', m1 = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres',
'api_url': 'http://127.0.0.1:8008/patroni', 'xlog_location': 4}) 'api_url': 'http://127.0.0.1:8008/patroni', 'xlog_location': 4})
leader = Leader(0, 0, m1) if leader else None leader = Leader(0, 0, m1) if leader else None
@@ -45,24 +56,36 @@ def get_cluster_initialized_without_leader(leader=False, failover=None, sync=Non
'scheduled_restart': {'schedule': "2100-01-01 10:53:07.560445+00:00", 'scheduled_restart': {'schedule': "2100-01-01 10:53:07.560445+00:00",
'postgres_version': '99.0.0'}}) 'postgres_version': '99.0.0'}})
syncstate = SyncState(0 if sync else None, sync and sync[0], sync and sync[1]) syncstate = SyncState(0 if sync else None, sync and sync[0], sync and sync[1])
return get_cluster(True, leader, [m1, m2], failover, syncstate) return get_cluster(SYSID, leader, [m1, m2], failover, syncstate, cluster_config)
def get_cluster_initialized_with_leader(failover=None, sync=None): def get_cluster_initialized_with_leader(failover=None, sync=None):
return get_cluster_initialized_without_leader(leader=True, failover=failover, sync=sync) return get_cluster_initialized_without_leader(leader=True, failover=failover, sync=sync)
def get_cluster_initialized_with_only_leader(failover=None): def get_cluster_initialized_with_only_leader(failover=None, cluster_config=None):
leader = get_cluster_initialized_without_leader(leader=True, failover=failover).leader leader = get_cluster_initialized_without_leader(leader=True, failover=failover).leader
return get_cluster(True, leader, [leader], failover, None) return get_cluster(True, leader, [leader], failover, None, cluster_config)
def get_node_status(reachable=True, in_recovery=True, wal_position=10, nofailover=False, watchdog_failed=False): def get_standby_cluster_initialized_with_only_leader(failover=None, sync=None):
return get_cluster_initialized_with_only_leader(
cluster_config=ClusterConfig(1, {
"standby_cluster": {
"host": "localhost",
"port": 5432,
"primary_slot_name": "",
}}, 1)
)
def get_node_status(reachable=True, in_recovery=True, timeline=2,
wal_position=10, nofailover=False, watchdog_failed=False):
def fetch_node_status(e): def fetch_node_status(e):
tags = {} tags = {}
if nofailover: if nofailover:
tags['nofailover'] = True tags['nofailover'] = True
return _MemberStatus(e, reachable, in_recovery, wal_position, tags, watchdog_failed) return _MemberStatus(e, reachable, in_recovery, timeline, wal_position, tags, watchdog_failed)
return fetch_node_status return fetch_node_status
@@ -95,7 +118,13 @@ zookeeper:
hosts: [localhost] hosts: [localhost]
port: 8181 port: 8181
""" """
# We rely on sys.argv in Config, so it's necessary to reset
# all the extra values that are coming from py.test
sys.argv = sys.argv[:1]
self.config = Config() self.config = Config()
self.config.set_dynamic_configuration({'maximum_lag_on_failover': 5})
self.version = '1.5.7'
self.postgresql = p self.postgresql = p
self.dcs = d self.dcs = d
self.api = Mock() self.api = Mock()
@@ -120,15 +149,17 @@ def run_async(self, func, args=()):
@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))
@patch.object(Postgresql, 'controldata', Mock(return_value={'Database system identifier': '1234567890'})) @patch.object(Postgresql, 'controldata', Mock(return_value={'Database system identifier': SYSID}))
@patch.object(Postgresql, 'sync_replication_slots', Mock()) @patch.object(SlotsHandler, 'sync_replication_slots', Mock())
@patch.object(Postgresql, 'write_pg_hba', Mock()) @patch.object(ConfigHandler, 'append_pg_hba', Mock())
@patch.object(Postgresql, 'write_pgpass', Mock(return_value={})) @patch.object(Postgresql, 'write_pgpass', Mock(return_value={}))
@patch.object(Postgresql, 'write_recovery_conf', Mock()) @patch.object(ConfigHandler, 'write_recovery_conf', Mock())
@patch.object(Postgresql, 'query', Mock()) @patch.object(Postgresql, 'query', Mock())
@patch.object(Postgresql, 'checkpoint', Mock()) @patch.object(Postgresql, 'checkpoint', Mock())
@patch.object(Postgresql, 'call_nowait', Mock()) @patch.object(CancellableSubprocess, 'call', Mock(return_value=0))
@patch.object(Postgresql, 'cancellable_subprocess_call', Mock(return_value=0)) @patch.object(Postgresql, 'get_local_timeline_lsn_from_replication_connection', Mock(return_value=[2, 10]))
@patch.object(Postgresql, 'get_master_timeline', Mock(return_value=2))
@patch.object(ConfigHandler, 'restore_configuration_files', Mock())
@patch.object(etcd.Client, 'write', etcd_write) @patch.object(etcd.Client, 'write', etcd_write)
@patch.object(etcd.Client, 'read', etcd_read) @patch.object(etcd.Client, 'read', etcd_read)
@patch.object(etcd.Client, 'delete', Mock(side_effect=etcd.EtcdException)) @patch.object(etcd.Client, 'delete', Mock(side_effect=etcd.EtcdException))
@@ -137,22 +168,15 @@ def run_async(self, func, args=()):
@patch('patroni.async_executor.AsyncExecutor.run_async', run_async) @patch('patroni.async_executor.AsyncExecutor.run_async', run_async)
@patch('subprocess.call', Mock(return_value=0)) @patch('subprocess.call', Mock(return_value=0))
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
class TestHa(unittest.TestCase): class TestHa(PostgresInit):
@patch('socket.getaddrinfo', socket_getaddrinfo) @patch('socket.getaddrinfo', socket_getaddrinfo)
@patch('psycopg2.connect', psycopg2_connect)
@patch('patroni.dcs.dcs_modules', Mock(return_value=['patroni.dcs.foo', 'patroni.dcs.etcd'])) @patch('patroni.dcs.dcs_modules', Mock(return_value=['patroni.dcs.foo', 'patroni.dcs.etcd']))
@patch.object(etcd.Client, 'read', etcd_read) @patch.object(etcd.Client, 'read', etcd_read)
def setUp(self): def setUp(self):
super(TestHa, self).setUp()
with patch.object(Client, 'machines') as mock_machines: with patch.object(Client, 'machines') as mock_machines:
mock_machines.__get__ = Mock(return_value=['http://remotehost:2379']) mock_machines.__get__ = Mock(return_value=['http://remotehost:2379'])
self.p = Postgresql({'name': 'postgresql0', 'scope': 'dummy', 'listen': '127.0.0.1:5432',
'data_dir': 'data/postgresql0', 'retry_timeout': 10,
'maximum_lag_on_failover': 5,
'authentication': {'superuser': {'username': 'foo', 'password': 'bar'},
'replication': {'username': '', 'password': ''}},
'parameters': {'wal_level': 'hot_standby', 'max_replication_slots': 5, 'foo': 'bar',
'hot_standby': 'on', 'max_wal_senders': 5, 'wal_keep_segments': 8}})
self.p.set_state('running') self.p.set_state('running')
self.p.set_role('replica') self.p.set_role('replica')
self.p.postmaster_start_time = MagicMock(return_value=str(postmaster_start_time)) self.p.postmaster_start_time = MagicMock(return_value=str(postmaster_start_time))
@@ -161,7 +185,7 @@ class TestHa(unittest.TestCase):
'name': 'foo', 'retry_timeout': 10}}) 'name': 'foo', 'retry_timeout': 10}})
self.ha = Ha(MockPatroni(self.p, self.e)) self.ha = Ha(MockPatroni(self.p, self.e))
self.ha.old_cluster = self.e.get_cluster() self.ha.old_cluster = self.e.get_cluster()
self.ha.cluster = get_cluster_not_initialized_without_leader() self.ha.cluster = get_cluster_initialized_without_leader()
self.ha.load_cluster_from_dcs = Mock() self.ha.load_cluster_from_dcs = Mock()
def test_update_lock(self): def test_update_lock(self):
@@ -173,50 +197,77 @@ class TestHa(unittest.TestCase):
self.p.replica_cached_timeline = Mock(side_effect=Exception) self.p.replica_cached_timeline = Mock(side_effect=Exception)
self.ha.touch_member() self.ha.touch_member()
def test_is_leader(self):
self.assertFalse(self.ha.is_leader())
def test_start_as_replica(self): def test_start_as_replica(self):
self.p.is_healthy = false self.p.is_healthy = false
self.assertEquals(self.ha.run_cycle(), 'starting as a secondary') self.assertEqual(self.ha.run_cycle(), 'starting as a secondary')
@patch('patroni.dcs.etcd.Etcd.initialize', return_value=True)
def test_bootstrap_as_standby_leader(self, initialize):
self.p.data_directory_empty = true
self.ha.cluster = get_cluster_not_initialized_without_leader(cluster_config=ClusterConfig(0, {}, 0))
self.ha.cluster.is_unlocked = true
self.ha.patroni.config._dynamic_configuration = {"standby_cluster": {"port": 5432}}
self.assertEqual(self.ha.run_cycle(), 'trying to bootstrap a new standby leader')
def test_bootstrap_waiting_for_standby_leader(self):
self.p.data_directory_empty = true
self.ha.cluster = get_cluster_initialized_without_leader()
self.ha.cluster.config.data.update({'standby_cluster': {'port': 5432}})
self.assertEqual(self.ha.run_cycle(), 'waiting for standby_leader to bootstrap')
@patch.object(Cluster, 'get_clone_member',
Mock(return_value=Member(0, 'test', 1, {'api_url': 'http://127.0.0.1:8011/patroni',
'conn_url': 'postgres://127.0.0.1:5432/postgres'})))
@patch.object(Bootstrap, 'create_replica', Mock(return_value=0))
def test_start_as_cascade_replica_in_standby_cluster(self):
self.p.data_directory_empty = true
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.cluster.is_unlocked = false
self.assertEqual(self.ha.run_cycle(), "trying to bootstrap from replica 'test'")
def test_recover_replica_failed(self): def test_recover_replica_failed(self):
self.p.controldata = lambda: {'Database cluster state': 'in recovery'} self.p.controldata = lambda: {'Database cluster state': 'in recovery', 'Database system identifier': SYSID}
self.p.is_running = false self.p.is_running = false
self.p.follow = false self.p.follow = false
self.assertEquals(self.ha.run_cycle(), 'starting as a secondary') self.assertEqual(self.ha.run_cycle(), 'starting as a secondary')
self.assertEquals(self.ha.run_cycle(), 'failed to start postgres') self.assertEqual(self.ha.run_cycle(), 'failed to start postgres')
def test_recover_former_master(self): def test_recover_former_master(self):
self.p.follow = false self.p.follow = false
self.p.is_running = false self.p.is_running = false
self.p.name = 'leader' self.p.name = 'leader'
self.p.set_role('master') self.p.set_role('master')
self.p.controldata = lambda: {'Database cluster state': 'shut down'} self.p.controldata = lambda: {'Database cluster state': 'shut down', 'Database system identifier': SYSID}
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.run_cycle(), 'starting as readonly because i had the session lock') self.assertEqual(self.ha.run_cycle(), 'starting as readonly because i had the session lock')
@patch.object(Postgresql, 'fix_cluster_state', Mock()) @patch.object(Postgresql, 'fix_cluster_state', Mock())
def test_crash_recovery(self): def test_crash_recovery(self):
self.p.is_running = false self.p.is_running = false
self.p.controldata = lambda: {'Database cluster state': 'in production'} self.p.controldata = lambda: {'Database cluster state': 'in production', 'Database system identifier': SYSID}
self.assertEquals(self.ha.run_cycle(), 'doing crash recovery in a single user mode') self.assertEqual(self.ha.run_cycle(), 'doing crash recovery in a single user mode')
@patch.object(Postgresql, 'rewind_needed_and_possible', Mock(return_value=True)) @patch.object(Rewind, 'rewind_or_reinitialize_needed_and_possible', Mock(return_value=True))
@patch.object(Rewind, 'can_rewind', PropertyMock(return_value=True))
def test_recover_with_rewind(self): def test_recover_with_rewind(self):
self.p.is_running = false self.p.is_running = false
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.run_cycle(), 'running pg_rewind from leader') self.assertEqual(self.ha.run_cycle(), 'running pg_rewind from leader')
@patch.object(Postgresql, 'can_rewind', PropertyMock(return_value=True)) @patch.object(Rewind, 'rewind_or_reinitialize_needed_and_possible', Mock(return_value=True))
@patch.object(Postgresql, 'fix_cluster_state', Mock()) @patch.object(Bootstrap, 'create_replica', Mock(return_value=1))
def test_single_user_after_recover_failed(self): def test_recover_with_reinitialize(self):
self.p.controldata = lambda: {'Database cluster state': 'in recovery'}
self.p.is_running = false self.p.is_running = false
self.p.follow = false self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.run_cycle(), 'starting as a secondary') self.assertEqual(self.ha.run_cycle(), 'reinitializing due to diverged timelines')
self.assertEquals(self.ha.run_cycle(), 'fixing cluster state in a single user mode')
@patch('sys.exit', return_value=1) @patch('sys.exit', return_value=1)
@patch('patroni.ha.Ha.sysid_valid', MagicMock(return_value=True)) @patch('patroni.ha.Ha.sysid_valid', MagicMock(return_value=True))
def test_sysid_no_match(self, exit_mock): def test_sysid_no_match(self, exit_mock):
self.p.controldata = lambda: {'Database cluster state': 'in recovery', 'Database system identifier': '123'}
self.ha.run_cycle() self.ha.run_cycle()
exit_mock.assert_called_once_with(1) exit_mock.assert_called_once_with(1)
@@ -225,129 +276,131 @@ class TestHa(unittest.TestCase):
self.p.is_leader = false self.p.is_leader = false
self.p.is_healthy = true self.p.is_healthy = true
self.ha.has_lock = true self.ha.has_lock = true
self.p.controldata = lambda: {'Database cluster state': 'in production'} self.p.controldata = lambda: {'Database cluster state': 'in production', 'Database system identifier': SYSID}
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader because i had the session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader because i had the session lock')
@patch('psycopg2.connect', psycopg2_connect) @patch('psycopg2.connect', psycopg2_connect)
def test_acquire_lock_as_master(self): def test_acquire_lock_as_master(self):
self.assertEquals(self.ha.run_cycle(), 'acquired session lock as a leader') self.assertEqual(self.ha.run_cycle(), 'acquired session lock as a leader')
def test_promoted_by_acquiring_lock(self): def test_promoted_by_acquiring_lock(self):
self.ha.is_healthiest_node = true self.ha.is_healthiest_node = true
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock')
def test_long_promote(self): def test_long_promote(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.ha.has_lock = true self.ha.has_lock = true
self.p.is_leader = false self.p.is_leader = false
self.p.set_role('master') self.p.set_role('master')
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
def test_demote_after_failing_to_obtain_lock(self): def test_demote_after_failing_to_obtain_lock(self):
self.ha.acquire_lock = false self.ha.acquire_lock = false
self.assertEquals(self.ha.run_cycle(), 'demoted self after trying and failing to obtain lock') self.assertEqual(self.ha.run_cycle(), 'demoted self after trying and failing to obtain lock')
def test_follow_new_leader_after_failing_to_obtain_lock(self): def test_follow_new_leader_after_failing_to_obtain_lock(self):
self.ha.is_healthiest_node = true self.ha.is_healthiest_node = true
self.ha.acquire_lock = false self.ha.acquire_lock = false
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'following new leader after trying and failing to obtain lock') self.assertEqual(self.ha.run_cycle(), 'following new leader after trying and failing to obtain lock')
def test_demote_because_not_healthiest(self): def test_demote_because_not_healthiest(self):
self.ha.is_healthiest_node = false self.ha.is_healthiest_node = false
self.assertEquals(self.ha.run_cycle(), 'demoting self because i am not the healthiest node') self.assertEqual(self.ha.run_cycle(), 'demoting self because i am not the healthiest node')
def test_follow_new_leader_because_not_healthiest(self): def test_follow_new_leader_because_not_healthiest(self):
self.ha.is_healthiest_node = false self.ha.is_healthiest_node = false
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'following a different leader because i am not the healthiest node') self.assertEqual(self.ha.run_cycle(), 'following a different leader because i am not the healthiest node')
def test_promote_because_have_lock(self): def test_promote_because_have_lock(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.ha.has_lock = true self.ha.has_lock = true
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader because i had the session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader because i had the session lock')
def test_promote_without_watchdog(self): def test_promote_without_watchdog(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.ha.has_lock = true self.ha.has_lock = true
self.p.is_leader = true self.p.is_leader = true
with patch.object(Watchdog, 'activate', Mock(return_value=False)): with patch.object(Watchdog, 'activate', Mock(return_value=False)):
self.assertEquals(self.ha.run_cycle(), 'Demoting self because watchdog could not be activated') self.assertEqual(self.ha.run_cycle(), 'Demoting self because watchdog could not be activated')
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'Not promoting self because watchdog could not be activated') self.assertEqual(self.ha.run_cycle(), 'Not promoting self because watchdog could not be activated')
def test_leader_with_lock(self): def test_leader_with_lock(self):
self.ha.cluster = get_cluster_initialized_with_leader()
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.ha.has_lock = true self.ha.has_lock = true
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
def test_demote_because_not_having_lock(self): def test_demote_because_not_having_lock(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
with patch.object(Watchdog, 'is_running', PropertyMock(return_value=True)): with patch.object(Watchdog, 'is_running', PropertyMock(return_value=True)):
self.assertEquals(self.ha.run_cycle(), 'demoting self because i do not have the lock and i was a leader') self.assertEqual(self.ha.run_cycle(), 'demoting self because i do not have the lock and i was a leader')
def test_demote_because_update_lock_failed(self): def test_demote_because_update_lock_failed(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.ha.has_lock = true self.ha.has_lock = true
self.ha.update_lock = false self.ha.update_lock = false
self.assertEquals(self.ha.run_cycle(), 'demoted self because failed to update leader lock in DCS') self.assertEqual(self.ha.run_cycle(), 'demoted self because failed to update leader lock in DCS')
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'not promoting because failed to update leader lock in DCS') self.assertEqual(self.ha.run_cycle(), 'not promoting because failed to update leader lock in DCS')
def test_follow(self): def test_follow(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'no action. i am a secondary and i am following a leader') self.assertEqual(self.ha.run_cycle(), 'no action. i am a secondary and i am following a leader')
self.ha.patroni.replicatefrom = "foo" self.ha.patroni.replicatefrom = "foo"
self.assertEquals(self.ha.run_cycle(), 'no action. i am a secondary and i am following a leader') self.assertEqual(self.ha.run_cycle(), 'no action. i am a secondary and i am following a leader')
def test_follow_in_pause(self): def test_follow_in_pause(self):
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.ha.is_paused = true self.ha.is_paused = true
self.assertEquals(self.ha.run_cycle(), 'PAUSE: continue to run as master without lock') self.assertEqual(self.ha.run_cycle(), 'PAUSE: continue to run as master without lock')
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'PAUSE: no action') self.assertEqual(self.ha.run_cycle(), 'PAUSE: no action')
@patch.object(Postgresql, 'rewind_needed_and_possible', Mock(return_value=True)) @patch.object(Rewind, 'rewind_or_reinitialize_needed_and_possible', Mock(return_value=True))
@patch.object(Rewind, 'can_rewind', PropertyMock(return_value=True))
def test_follow_triggers_rewind(self): def test_follow_triggers_rewind(self):
self.p.is_leader = false self.p.is_leader = false
self.p.trigger_check_diverged_lsn() self.ha._rewind.trigger_check_diverged_lsn()
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.run_cycle(), 'running pg_rewind from leader') self.assertEqual(self.ha.run_cycle(), 'running pg_rewind from leader')
def test_no_etcd_connection_master_demote(self): def test_no_etcd_connection_master_demote(self):
self.ha.load_cluster_from_dcs = Mock(side_effect=DCSError('Etcd is not responding properly')) self.ha.load_cluster_from_dcs = Mock(side_effect=DCSError('Etcd is not responding properly'))
self.assertEquals(self.ha.run_cycle(), 'demoted self because DCS is not accessible and i was a leader') self.assertEqual(self.ha.run_cycle(), 'demoted self because DCS is not accessible and i was a leader')
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
def test_bootstrap_from_another_member(self): def test_bootstrap_from_another_member(self):
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.bootstrap(), 'trying to bootstrap from replica \'other\'') self.assertEqual(self.ha.bootstrap(), 'trying to bootstrap from replica \'other\'')
def test_bootstrap_waiting_for_leader(self): def test_bootstrap_waiting_for_leader(self):
self.ha.cluster = get_cluster_initialized_without_leader() self.ha.cluster = get_cluster_initialized_without_leader()
self.assertEquals(self.ha.bootstrap(), 'waiting for leader to bootstrap') self.assertEqual(self.ha.bootstrap(), 'waiting for leader to bootstrap')
def test_bootstrap_without_leader(self): def test_bootstrap_without_leader(self):
self.ha.cluster = get_cluster_initialized_without_leader() self.ha.cluster = get_cluster_initialized_without_leader()
self.p.can_create_replica_without_replication_connection = MagicMock(return_value=True) self.p.can_create_replica_without_replication_connection = MagicMock(return_value=True)
self.assertEquals(self.ha.bootstrap(), 'trying to bootstrap (without leader)') self.assertEqual(self.ha.bootstrap(), 'trying to bootstrap (without leader)')
def test_bootstrap_initialize_lock_failed(self): def test_bootstrap_initialize_lock_failed(self):
self.ha.cluster = get_cluster_not_initialized_without_leader() self.ha.cluster = get_cluster_not_initialized_without_leader()
self.assertEquals(self.ha.bootstrap(), 'failed to acquire initialize lock') self.assertEqual(self.ha.bootstrap(), 'failed to acquire initialize lock')
def test_bootstrap_initialized_new_cluster(self): def test_bootstrap_initialized_new_cluster(self):
self.ha.cluster = get_cluster_not_initialized_without_leader() self.ha.cluster = get_cluster_not_initialized_without_leader()
self.e.initialize = true self.e.initialize = true
self.assertEquals(self.ha.bootstrap(), 'trying to bootstrap a new cluster') self.assertEqual(self.ha.bootstrap(), 'trying to bootstrap a new cluster')
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'waiting for end of recovery after bootstrap') self.assertEqual(self.ha.run_cycle(), 'waiting for end of recovery after bootstrap')
self.p.is_leader = true self.p.is_leader = true
self.assertEquals(self.ha.run_cycle(), 'running post_bootstrap') self.assertEqual(self.ha.run_cycle(), 'running post_bootstrap')
self.assertEquals(self.ha.run_cycle(), 'initialized a new cluster') self.assertEqual(self.ha.run_cycle(), 'initialized a new cluster')
def test_bootstrap_release_initialize_key_on_failure(self): def test_bootstrap_release_initialize_key_on_failure(self):
self.ha.cluster = get_cluster_not_initialized_without_leader() self.ha.cluster = get_cluster_not_initialized_without_leader()
@@ -363,7 +416,7 @@ class TestHa(unittest.TestCase):
self.p.is_running.return_value = MockPostmaster() self.p.is_running.return_value = MockPostmaster()
self.p.is_leader = true self.p.is_leader = true
with patch.object(Watchdog, 'activate', Mock(return_value=False)): with patch.object(Watchdog, 'activate', Mock(return_value=False)):
self.assertEquals(self.ha.post_bootstrap(), 'running post_bootstrap') self.assertEqual(self.ha.post_bootstrap(), 'running post_bootstrap')
self.assertRaises(PatroniException, self.ha.post_bootstrap) self.assertRaises(PatroniException, self.ha.post_bootstrap)
@patch('psycopg2.connect', psycopg2_connect) @patch('psycopg2.connect', psycopg2_connect)
@@ -380,35 +433,35 @@ class TestHa(unittest.TestCase):
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
def test_restart(self): def test_restart(self):
self.assertEquals(self.ha.restart({}), (True, 'restarted successfully')) self.assertEqual(self.ha.restart({}), (True, 'restarted successfully'))
self.p.restart = Mock(return_value=None) self.p.restart = Mock(return_value=None)
self.assertEquals(self.ha.restart({}), (False, 'postgres is still starting')) self.assertEqual(self.ha.restart({}), (False, 'postgres is still starting'))
self.p.restart = false self.p.restart = false
self.assertEquals(self.ha.restart({}), (False, 'restart failed')) self.assertEqual(self.ha.restart({}), (False, 'restart failed'))
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.ha.reinitialize() self.ha.reinitialize()
self.assertEquals(self.ha.restart({}), (False, 'reinitialize already in progress')) self.assertEqual(self.ha.restart({}), (False, 'reinitialize already in progress'))
with patch.object(self.ha, "restart_matches", return_value=False): with patch.object(self.ha, "restart_matches", return_value=False):
self.assertEquals(self.ha.restart({'foo': 'bar'}), (False, "restart conditions are not satisfied")) self.assertEqual(self.ha.restart({'foo': 'bar'}), (False, "restart conditions are not satisfied"))
@patch('os.kill', Mock()) @patch('os.kill', Mock())
def test_restart_in_progress(self): def test_restart_in_progress(self):
with patch('patroni.async_executor.AsyncExecutor.busy', PropertyMock(return_value=True)): with patch('patroni.async_executor.AsyncExecutor.busy', PropertyMock(return_value=True)):
self.ha.restart({}, run_async=True) self.ha.restart({}, run_async=True)
self.assertTrue(self.ha.restart_scheduled()) self.assertTrue(self.ha.restart_scheduled())
self.assertEquals(self.ha.run_cycle(), 'restart in progress') self.assertEqual(self.ha.run_cycle(), 'restart in progress')
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.run_cycle(), 'restart in progress') self.assertEqual(self.ha.run_cycle(), 'restart in progress')
self.ha.has_lock = true self.ha.has_lock = true
self.assertEquals(self.ha.run_cycle(), 'updated leader lock during restart') self.assertEqual(self.ha.run_cycle(), 'updated leader lock during restart')
self.ha.update_lock = false self.ha.update_lock = false
self.p.set_role('master') self.p.set_role('master')
with patch('patroni.async_executor.CriticalTask.cancel', Mock(return_value=False)): with patch('patroni.async_executor.CriticalTask.cancel', Mock(return_value=False)):
with patch('patroni.postgresql.Postgresql.terminate_starting_postmaster') as mock_terminate: with patch('patroni.postgresql.Postgresql.terminate_starting_postmaster') as mock_terminate:
self.assertEquals(self.ha.run_cycle(), 'lost leader lock during restart') self.assertEqual(self.ha.run_cycle(), 'lost leader lock during restart')
mock_terminate.assert_called() mock_terminate.assert_called()
@patch('requests.get', requests_get) @patch('requests.get', requests_get)
@@ -416,25 +469,27 @@ class TestHa(unittest.TestCase):
self.ha.fetch_node_status = get_node_status() self.ha.fetch_node_status = get_node_status()
self.ha.has_lock = true self.ha.has_lock = true
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', '', None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', '', None))
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', self.p.name, None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', self.p.name, None))
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', 'blabla', None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', 'blabla', None))
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
f = Failover(0, self.p.name, '', None) f = Failover(0, self.p.name, '', None)
self.ha.cluster = get_cluster_initialized_with_leader(f) self.ha.cluster = get_cluster_initialized_with_leader(f)
self.assertEquals(self.ha.run_cycle(), 'manual failover: demoting myself') self.assertEqual(self.ha.run_cycle(), 'manual failover: demoting myself')
self.p.rewind_needed_and_possible = true self.ha._rewind.rewind_or_reinitialize_needed_and_possible = true
self.assertEquals(self.ha.run_cycle(), 'manual failover: demoting myself') self.assertEqual(self.ha.run_cycle(), 'manual failover: demoting myself')
self.ha.fetch_node_status = get_node_status(nofailover=True) self.ha.fetch_node_status = get_node_status(nofailover=True)
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
self.ha.fetch_node_status = get_node_status(watchdog_failed=True) self.ha.fetch_node_status = get_node_status(watchdog_failed=True)
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
self.ha.fetch_node_status = get_node_status(timeline=1)
self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
self.ha.fetch_node_status = get_node_status(wal_position=1) self.ha.fetch_node_status = get_node_status(wal_position=1)
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
# manual failover from the previous leader to us won't happen if we hold the nofailover flag # manual failover from the previous leader to us won't happen if we hold the nofailover flag
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, None))
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
# Failover scheduled time must include timezone # Failover scheduled time must include timezone
scheduled = datetime.datetime.now() scheduled = datetime.datetime.now()
@@ -443,19 +498,19 @@ class TestHa(unittest.TestCase):
scheduled = datetime.datetime.utcnow().replace(tzinfo=tzutc) scheduled = datetime.datetime.utcnow().replace(tzinfo=tzutc)
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled))
self.assertEquals('no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('no action. i am the leader with the lock', self.ha.run_cycle())
scheduled = scheduled + datetime.timedelta(seconds=30) scheduled = scheduled + datetime.timedelta(seconds=30)
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled))
self.assertEquals('no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('no action. i am the leader with the lock', self.ha.run_cycle())
scheduled = scheduled + datetime.timedelta(seconds=-600) scheduled = scheduled + datetime.timedelta(seconds=-600)
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled))
self.assertEquals('no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('no action. i am the leader with the lock', self.ha.run_cycle())
scheduled = None scheduled = None
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled))
self.assertEquals('no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('no action. i am the leader with the lock', self.ha.run_cycle())
@patch('requests.get', requests_get) @patch('requests.get', requests_get)
def test_manual_failover_from_leader_in_pause(self): def test_manual_failover_from_leader_in_pause(self):
@@ -463,9 +518,9 @@ class TestHa(unittest.TestCase):
self.ha.is_paused = true self.ha.is_paused = true
scheduled = datetime.datetime.now() scheduled = datetime.datetime.now()
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, 'blabla', self.p.name, scheduled))
self.assertEquals('PAUSE: no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('PAUSE: no action. i am the leader with the lock', self.ha.run_cycle())
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, self.p.name, '', None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, self.p.name, '', None))
self.assertEquals('PAUSE: no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('PAUSE: no action. i am the leader with the lock', self.ha.run_cycle())
@patch('requests.get', requests_get) @patch('requests.get', requests_get)
def test_manual_failover_from_leader_in_synchronous_mode(self): def test_manual_failover_from_leader_in_synchronous_mode(self):
@@ -475,48 +530,48 @@ class TestHa(unittest.TestCase):
self.ha.is_failover_possible = false self.ha.is_failover_possible = false
self.ha.process_sync_replication = Mock() self.ha.process_sync_replication = Mock()
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, self.p.name, 'a', None), (self.p.name, None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, self.p.name, 'a', None), (self.p.name, None))
self.assertEquals('no action. i am the leader with the lock', self.ha.run_cycle()) self.assertEqual('no action. i am the leader with the lock', self.ha.run_cycle())
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, self.p.name, 'a', None), (self.p.name, 'a')) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, self.p.name, 'a', None), (self.p.name, 'a'))
self.ha.is_failover_possible = true self.ha.is_failover_possible = true
self.assertEquals('manual failover: demoting myself', self.ha.run_cycle()) self.assertEqual('manual failover: demoting myself', self.ha.run_cycle())
@patch('requests.get', requests_get) @patch('requests.get', requests_get)
def test_manual_failover_process_no_leader(self): def test_manual_failover_process_no_leader(self):
self.p.is_leader = false self.p.is_leader = false
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', self.p.name, None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', self.p.name, None))
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock')
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', 'leader', None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', 'leader', None))
self.p.set_role('replica') self.p.set_role('replica')
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock')
self.ha.fetch_node_status = get_node_status() # accessible, in_recovery self.ha.fetch_node_status = get_node_status() # accessible, in_recovery
self.assertEquals(self.ha.run_cycle(), 'following a different leader because i am not the healthiest node') self.assertEqual(self.ha.run_cycle(), 'following a different leader because i am not the healthiest node')
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, self.p.name, '', None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, self.p.name, '', None))
self.assertEquals(self.ha.run_cycle(), 'following a different leader because i am not the healthiest node') self.assertEqual(self.ha.run_cycle(), 'following a different leader because i am not the healthiest node')
self.ha.fetch_node_status = get_node_status(reachable=False) # inaccessible, in_recovery self.ha.fetch_node_status = get_node_status(reachable=False) # inaccessible, in_recovery
self.p.set_role('replica') self.p.set_role('replica')
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock')
# set failover flag to True for all members of the cluster # set failover flag to True for all members of the cluster
# this should elect the current member, as we are not going to call the API for it. # this should elect the current member, as we are not going to call the API for it.
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', 'other', None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', 'other', None))
self.ha.fetch_node_status = get_node_status(nofailover=True) # accessible, in_recovery self.ha.fetch_node_status = get_node_status(nofailover=True) # accessible, in_recovery
self.p.set_role('replica') self.p.set_role('replica')
self.assertEquals(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock') self.assertEqual(self.ha.run_cycle(), 'promoted self to leader by acquiring session lock')
# same as previous, but set the current member to nofailover. In no case it should be elected as a leader # same as previous, but set the current member to nofailover. In no case it should be elected as a leader
self.ha.patroni.nofailover = True self.ha.patroni.nofailover = True
self.assertEquals(self.ha.run_cycle(), 'following a different leader because I am not allowed to promote') self.assertEqual(self.ha.run_cycle(), 'following a different leader because I am not allowed to promote')
def test_manual_failover_process_no_leader_in_pause(self): def test_manual_failover_process_no_leader_in_pause(self):
self.ha.is_paused = true self.ha.is_paused = true
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', 'other', None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, '', 'other', None))
self.assertEquals(self.ha.run_cycle(), 'PAUSE: continue to run as master without lock') self.assertEqual(self.ha.run_cycle(), 'PAUSE: continue to run as master without lock')
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, 'leader', '', None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, 'leader', '', None))
self.assertEquals(self.ha.run_cycle(), 'PAUSE: continue to run as master without lock') self.assertEqual(self.ha.run_cycle(), 'PAUSE: continue to run as master without lock')
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, 'leader', 'blabla', None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, 'leader', 'blabla', None))
self.assertEquals('PAUSE: acquired session lock as a leader', self.ha.run_cycle()) self.assertEqual('PAUSE: acquired session lock as a leader', self.ha.run_cycle())
self.p.is_leader = false self.p.is_leader = false
self.p.set_role('replica') self.p.set_role('replica')
self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, 'leader', self.p.name, None)) self.ha.cluster = get_cluster_initialized_without_leader(failover=Failover(0, 'leader', self.p.name, None))
self.assertEquals(self.ha.run_cycle(), 'PAUSE: promoted self to leader by acquiring session lock') self.assertEqual(self.ha.run_cycle(), 'PAUSE: promoted self to leader by acquiring session lock')
def test_is_healthiest_node(self): def test_is_healthiest_node(self):
self.ha.state_handler.is_leader = false self.ha.state_handler.is_leader = false
@@ -530,7 +585,9 @@ class TestHa(unittest.TestCase):
self.ha.is_paused = true self.ha.is_paused = true
self.assertFalse(self.ha.is_healthiest_node()) self.assertFalse(self.ha.is_healthiest_node())
@patch('requests.get', requests_get)
def test__is_healthiest_node(self): def test__is_healthiest_node(self):
self.ha.cluster = get_cluster_initialized_without_leader(sync=('postgresql1', self.p.name))
self.assertTrue(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertTrue(self.ha._is_healthiest_node(self.ha.old_cluster.members))
self.p.is_leader = false self.p.is_leader = false
self.ha.fetch_node_status = get_node_status() # accessible, in_recovery self.ha.fetch_node_status = get_node_status() # accessible, in_recovery
@@ -539,8 +596,13 @@ class TestHa(unittest.TestCase):
self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members))
self.ha.fetch_node_status = get_node_status(wal_position=11) # accessible, in_recovery, wal position ahead self.ha.fetch_node_status = get_node_status(wal_position=11) # accessible, in_recovery, wal position ahead
self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members))
# 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)):
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)):
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):
self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members))
self.ha.patroni.nofailover = True self.ha.patroni.nofailover = True
self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members)) self.assertFalse(self.ha._is_healthiest_node(self.ha.old_cluster.members))
self.ha.patroni.nofailover = False self.ha.patroni.nofailover = False
@@ -597,11 +659,11 @@ class TestHa(unittest.TestCase):
def test_scheduled_restart(self): def test_scheduled_restart(self):
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
with patch.object(self.ha, "evaluate_scheduled_restart", Mock(return_value="restart scheduled")): with patch.object(self.ha, "evaluate_scheduled_restart", Mock(return_value="restart scheduled")):
self.assertEquals(self.ha.run_cycle(), "restart scheduled") self.assertEqual(self.ha.run_cycle(), "restart scheduled")
def test_restart_matches(self): def test_restart_matches(self):
self.p._role = 'replica' self.p._role = 'replica'
self.p.server_version = 90500 self.p._connection.server_version = 90500
self.p._pending_restart = True self.p._pending_restart = True
self.assertFalse(self.ha.restart_matches("master", "9.5.0", True)) self.assertFalse(self.ha.restart_matches("master", "9.5.0", True))
self.assertFalse(self.ha.restart_matches("replica", "9.4.3", True)) self.assertFalse(self.ha.restart_matches("replica", "9.4.3", True))
@@ -614,21 +676,82 @@ class TestHa(unittest.TestCase):
self.ha.is_paused = true self.ha.is_paused = true
self.p.name = 'leader' self.p.name = 'leader'
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEquals(self.ha.run_cycle(), 'PAUSE: removed leader lock because postgres is not running as master') self.assertEqual(self.ha.run_cycle(), 'PAUSE: removed leader lock because postgres is not running as master')
self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', self.p.name, None)) self.ha.cluster = get_cluster_initialized_with_leader(Failover(0, '', self.p.name, None))
self.assertEquals(self.ha.run_cycle(), 'PAUSE: waiting to become master after promote...') self.assertEqual(self.ha.run_cycle(), 'PAUSE: waiting to become master after promote...')
def test_process_healthy_standby_cluster_as_standby_leader(self):
self.p.is_leader = false
self.p.name = 'leader'
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.p.config.check_recovery_conf = true
self.assertEqual(self.ha.run_cycle(), 'promoted self to a standby leader because i had the session lock')
self.assertEqual(self.ha.run_cycle(), 'no action. i am the standby leader with the lock')
def test_process_healthy_standby_cluster_as_cascade_replica(self):
self.p.is_leader = false
self.p.name = 'replica'
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.assertEqual(self.ha.run_cycle(), 'no action. i am a secondary and i am following a standby leader')
with patch.object(Leader, 'conn_url', PropertyMock(return_value='')):
self.assertEqual(self.ha.run_cycle(), 'continue following the old known standby leader')
@patch('requests.get', requests_get)
def test_process_unhealthy_standby_cluster_as_standby_leader(self):
self.p.is_leader = false
self.p.name = 'leader'
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.cluster.is_unlocked = true
self.ha.sysid_valid = true
self.p._sysid = True
self.assertEqual(self.ha.run_cycle(), 'promoted self to a standby leader by acquiring session lock')
@patch.object(Rewind, 'rewind_or_reinitialize_needed_and_possible', Mock(return_value=True))
@patch.object(Rewind, 'can_rewind', PropertyMock(return_value=True))
def test_process_unhealthy_standby_cluster_as_cascade_replica(self):
self.p.is_leader = false
self.p.name = 'replica'
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.is_unlocked = true
self.assertTrue(self.ha.run_cycle().startswith('running pg_rewind from remote_master:'))
def test_recover_unhealthy_leader_in_standby_cluster(self):
self.p.is_leader = false
self.p.name = 'leader'
self.p.is_running = false
self.p.follow = false
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.assertEqual(self.ha.run_cycle(), 'starting as a standby leader because i had the session lock')
def test_recover_unhealthy_unlocked_standby_cluster(self):
self.p.is_leader = false
self.p.name = 'leader'
self.p.is_running = false
self.p.follow = false
self.ha.cluster = get_standby_cluster_initialized_with_only_leader()
self.ha.cluster.is_unlocked = true
self.ha.has_lock = false
self.assertEqual(self.ha.run_cycle(), 'trying to follow a remote master because standby cluster is unhealthy')
def test_failed_to_update_lock_in_pause(self):
self.ha.update_lock = false
self.ha.is_paused = true
self.p.name = 'leader'
self.ha.cluster = get_cluster_initialized_with_leader()
self.assertEqual(self.ha.run_cycle(),
'PAUSE: continue to run as master after failing to update leader lock in DCS')
def test_postgres_unhealthy_in_pause(self): def test_postgres_unhealthy_in_pause(self):
self.ha.is_paused = true self.ha.is_paused = true
self.p.is_healthy = false self.p.is_healthy = false
self.assertEquals(self.ha.run_cycle(), 'PAUSE: postgres is not running') self.assertEqual(self.ha.run_cycle(), 'PAUSE: postgres is not running')
self.ha.has_lock = true self.ha.has_lock = true
self.assertEquals(self.ha.run_cycle(), 'PAUSE: removed leader lock because postgres is not running') self.assertEqual(self.ha.run_cycle(), 'PAUSE: removed leader lock because postgres is not running')
def test_no_etcd_connection_in_pause(self): def test_no_etcd_connection_in_pause(self):
self.ha.is_paused = true self.ha.is_paused = true
self.ha.load_cluster_from_dcs = Mock(side_effect=DCSError('Etcd is not responding properly')) self.ha.load_cluster_from_dcs = Mock(side_effect=DCSError('Etcd is not responding properly'))
self.assertEquals(self.ha.run_cycle(), 'PAUSE: DCS is not accessible') self.assertEqual(self.ha.run_cycle(), 'PAUSE: DCS is not accessible')
@patch('patroni.ha.Ha.update_lock', return_value=True) @patch('patroni.ha.Ha.update_lock', return_value=True)
@patch('patroni.ha.Ha.demote') @patch('patroni.ha.Ha.demote')
@@ -644,26 +767,26 @@ class TestHa(unittest.TestCase):
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.p.check_for_startup = true self.p.check_for_startup = true
self.p.time_in_state = lambda: 30 self.p.time_in_state = lambda: 30
self.assertEquals(self.ha.run_cycle(), 'PostgreSQL is still starting up, 270 seconds until timeout') self.assertEqual(self.ha.run_cycle(), 'PostgreSQL is still starting up, 270 seconds until timeout')
check_calls([(update_lock, True), (demote, False)]) check_calls([(update_lock, True), (demote, False)])
self.p.time_in_state = lambda: 350 self.p.time_in_state = lambda: 350
self.ha.fetch_node_status = get_node_status(reachable=False) # inaccessible, in_recovery self.ha.fetch_node_status = get_node_status(reachable=False) # inaccessible, in_recovery
self.assertEquals(self.ha.run_cycle(), self.assertEqual(self.ha.run_cycle(),
'master start has timed out, but continuing to wait because failover is not possible') 'master start has timed out, but continuing to wait because failover is not possible')
check_calls([(update_lock, True), (demote, False)]) check_calls([(update_lock, True), (demote, False)])
self.ha.fetch_node_status = get_node_status() # accessible, in_recovery self.ha.fetch_node_status = get_node_status() # accessible, in_recovery
self.assertEquals(self.ha.run_cycle(), 'stopped PostgreSQL because of startup timeout') self.assertEqual(self.ha.run_cycle(), 'stopped PostgreSQL because of startup timeout')
check_calls([(update_lock, True), (demote, True)]) check_calls([(update_lock, True), (demote, True)])
update_lock.return_value = False update_lock.return_value = False
self.assertEquals(self.ha.run_cycle(), 'stopped PostgreSQL while starting up because leader key was lost') self.assertEqual(self.ha.run_cycle(), 'stopped PostgreSQL while starting up because leader key was lost')
check_calls([(update_lock, True), (demote, True)]) check_calls([(update_lock, True), (demote, True)])
self.ha.has_lock = false self.ha.has_lock = false
self.p.is_leader = false self.p.is_leader = false
self.assertEquals(self.ha.run_cycle(), 'no action. i am a secondary and i am following a leader') self.assertEqual(self.ha.run_cycle(), 'no action. i am a secondary and i am following a leader')
check_calls([(update_lock, False), (demote, False)]) check_calls([(update_lock, False), (demote, False)])
def test_manual_failover_while_starting(self): def test_manual_failover_while_starting(self):
@@ -672,7 +795,7 @@ class TestHa(unittest.TestCase):
f = Failover(0, self.p.name, '', None) f = Failover(0, self.p.name, '', None)
self.ha.cluster = get_cluster_initialized_with_leader(f) self.ha.cluster = get_cluster_initialized_with_leader(f)
self.ha.fetch_node_status = get_node_status() # accessible, in_recovery self.ha.fetch_node_status = get_node_status() # accessible, in_recovery
self.assertEquals(self.ha.run_cycle(), 'manual failover: demoting myself') self.assertEqual(self.ha.run_cycle(), 'manual failover: demoting myself')
@patch('patroni.ha.Ha.demote') @patch('patroni.ha.Ha.demote')
def test_failover_immediately_on_zero_master_start_timeout(self, demote): def test_failover_immediately_on_zero_master_start_timeout(self, demote):
@@ -683,7 +806,7 @@ class TestHa(unittest.TestCase):
self.ha.has_lock = true self.ha.has_lock = true
self.ha.update_lock = true self.ha.update_lock = true
self.ha.fetch_node_status = get_node_status() # accessible, in_recovery self.ha.fetch_node_status = get_node_status() # accessible, in_recovery
self.assertEquals(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()
@patch('patroni.postgresql.Postgresql.follow') @patch('patroni.postgresql.Postgresql.follow')
@@ -695,7 +818,7 @@ class TestHa(unittest.TestCase):
def test_process_sync_replication(self): def test_process_sync_replication(self):
self.ha.has_lock = true self.ha.has_lock = true
mock_set_sync = self.p.set_synchronous_standby = Mock() mock_set_sync = self.p.config.set_synchronous_standby = Mock()
self.p.name = 'leader' self.p.name = 'leader'
# Test sync key removed when sync mode disabled # Test sync key removed when sync mode disabled
@@ -745,18 +868,22 @@ class TestHa(unittest.TestCase):
self.p.pick_synchronous_standby = Mock(return_value=('other2', True)) self.p.pick_synchronous_standby = Mock(return_value=('other2', True))
self.ha.run_cycle() self.ha.run_cycle()
self.ha.dcs.get_cluster.assert_called_once() self.ha.dcs.get_cluster.assert_called_once()
self.assertEquals(self.ha.dcs.write_sync_state.call_count, 2) self.assertEqual(self.ha.dcs.write_sync_state.call_count, 2)
# Test updating sync standby key failed due to race # Test updating sync standby key failed due to race
self.ha.dcs.write_sync_state = Mock(side_effect=[True, False]) self.ha.dcs.write_sync_state = Mock(side_effect=[True, False])
self.ha.run_cycle() self.ha.run_cycle()
self.assertEquals(self.ha.dcs.write_sync_state.call_count, 2) self.assertEqual(self.ha.dcs.write_sync_state.call_count, 2)
# Test updating sync standby key failed due to DCS being not accessible
self.ha.dcs.write_sync_state = Mock(return_value=True)
self.ha.dcs.get_cluster = Mock(side_effect=DCSError('foo'))
self.ha.run_cycle()
# Test changing sync standby failed due to race # Test changing sync standby failed due to race
self.ha.dcs.write_sync_state = Mock(return_value=True)
self.ha.dcs.get_cluster = Mock(return_value=get_cluster_initialized_with_leader(sync=('somebodyelse', None))) self.ha.dcs.get_cluster = Mock(return_value=get_cluster_initialized_with_leader(sync=('somebodyelse', None)))
self.ha.run_cycle() self.ha.run_cycle()
self.assertEquals(self.ha.dcs.write_sync_state.call_count, 1) self.assertEqual(self.ha.dcs.write_sync_state.call_count, 2)
# Test sync set to '*' when synchronous_mode_strict is enabled # Test sync set to '*' when synchronous_mode_strict is enabled
mock_set_sync.reset_mock() mock_set_sync.reset_mock()
@@ -768,7 +895,7 @@ class TestHa(unittest.TestCase):
def test_sync_replication_become_master(self): def test_sync_replication_become_master(self):
self.ha.is_synchronous_mode = true self.ha.is_synchronous_mode = true
mock_set_sync = self.p.set_synchronous_standby = Mock() mock_set_sync = self.p.config.set_synchronous_standby = Mock()
self.p.is_leader = false self.p.is_leader = false
self.p.set_role('replica') self.p.set_role('replica')
self.ha.has_lock = true self.ha.has_lock = true
@@ -777,7 +904,7 @@ class TestHa(unittest.TestCase):
self.ha.cluster = get_cluster_initialized_with_leader(sync=('other', None)) self.ha.cluster = get_cluster_initialized_with_leader(sync=('other', None))
# When we just became master nobody is sync # When we just became master nobody is sync
self.assertEquals(self.ha.enforce_master_role('msg', 'promote msg'), 'promote msg') self.assertEqual(self.ha.enforce_master_role('msg', 'promote msg'), 'promote msg')
mock_set_sync.assert_called_once_with(None) mock_set_sync.assert_called_once_with(None)
mock_write_sync.assert_called_once_with('leader', None, index=0) mock_write_sync.assert_called_once_with('leader', None, index=0)
@@ -805,7 +932,7 @@ class TestHa(unittest.TestCase):
self.ha.run_cycle() self.ha.run_cycle()
mock_acquire.assert_not_called() mock_acquire.assert_not_called()
mock_follow.assert_called_once() mock_follow.assert_called_once()
self.assertEquals(mock_follow.call_args[0][0], None) self.assertEqual(mock_follow.call_args[0][0], None)
mock_write_sync.assert_not_called() mock_write_sync.assert_not_called()
mock_follow.reset_mock() mock_follow.reset_mock()
@@ -856,15 +983,15 @@ class TestHa(unittest.TestCase):
def test_effective_tags(self): def test_effective_tags(self):
self.ha._disable_sync = True self.ha._disable_sync = True
self.assertEquals(self.ha.get_effective_tags(), {'foo': 'bar', 'nosync': True}) self.assertEqual(self.ha.get_effective_tags(), {'foo': 'bar', 'nosync': True})
self.ha._disable_sync = False self.ha._disable_sync = False
self.assertEquals(self.ha.get_effective_tags(), {'foo': 'bar'}) self.assertEqual(self.ha.get_effective_tags(), {'foo': 'bar'})
def test_restore_cluster_config(self): def test_restore_cluster_config(self):
self.ha.cluster.config.data.clear() self.ha.cluster.config.data.clear()
self.ha.has_lock = true self.ha.has_lock = true
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
def test_watch(self): def test_watch(self):
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
@@ -883,16 +1010,43 @@ class TestHa(unittest.TestCase):
self.ha.cluster = get_cluster_initialized_with_leader() self.ha.cluster = get_cluster_initialized_with_leader()
self.ha.has_lock = true self.ha.has_lock = true
self.p.data_directory_empty = true self.p.data_directory_empty = true
self.assertEquals(self.ha.run_cycle(), 'released leader key voluntarily as data dir empty and currently leader') self.assertEqual(self.ha.run_cycle(), 'released leader key voluntarily as data dir empty and currently leader')
self.assertEquals(self.p.role, 'uninitialized') self.assertEqual(self.p.role, 'uninitialized')
# as has_lock is mocked out, we need to fake the leader key release # as has_lock is mocked out, we need to fake the leader key release
self.ha.has_lock = false self.ha.has_lock = false
# will not say bootstrap from leader as replica can't self elect # will not say bootstrap from leader as replica can't self elect
self.assertEquals(self.ha.run_cycle(), "trying to bootstrap from replica 'other'") self.assertEqual(self.ha.run_cycle(), "trying to bootstrap from replica 'other'")
@patch('psycopg2.connect', psycopg2_connect)
def test_update_cluster_history(self): def test_update_cluster_history(self):
self.p.get_master_timeline = Mock(return_value=1)
self.ha.has_lock = true self.ha.has_lock = true
self.ha.cluster.is_unlocked = false self.ha.cluster.is_unlocked = false
self.assertEquals(self.ha.run_cycle(), 'no action. i am the leader with the lock') for tl in (1, 3):
self.p.get_master_timeline = Mock(return_value=tl)
self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
@patch('sys.exit', return_value=1)
@patch('requests.get', requests_get)
def test_abort_join(self, exit_mock):
self.ha.cluster = get_cluster_not_initialized_without_leader()
self.p.is_leader = false
self.ha.run_cycle()
exit_mock.assert_called_once_with(1)
def test_after_pause(self):
self.ha.has_lock = true
self.ha.cluster.is_unlocked = false
self.ha.is_paused = true
self.assertEqual(self.ha.run_cycle(), 'PAUSE: no action. i am the leader with the lock')
self.ha.is_paused = false
self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
@patch('psycopg2.connect', psycopg2_connect)
def test_permanent_logical_slots_after_promote(self):
config = ClusterConfig(1, {'slots': {'l': {'database': 'postgres', 'plugin': 'test_decoding'}}}, 1)
self.ha.cluster = get_cluster_initialized_without_leader(cluster_config=config)
self.assertEqual(self.ha.run_cycle(), 'acquired session lock as a leader')
self.ha.cluster = get_cluster_initialized_without_leader(leader=True, cluster_config=config)
self.ha.has_lock = true
self.assertEqual(self.ha.run_cycle(), 'no action. i am the leader with the lock')
+27 -6
View File
@@ -1,3 +1,4 @@
import time
import unittest import unittest
from mock import Mock, patch from mock import Mock, patch
@@ -33,13 +34,14 @@ class TestKubernetes(unittest.TestCase):
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', mock_list_namespaced_pod) @patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', mock_list_namespaced_pod)
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', 'retry_timeout': 10, 'labels': {'f': 'b'}})
with patch('time.time', Mock(return_value=1)): self.k.get_cluster()
def test_get_cluster(self):
with 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('time.time', Mock(return_value=time.time() + 31)):
self.k.get_cluster() self.k.get_cluster()
@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)
def test_get_cluster(self):
self.k.get_cluster()
with patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', Mock(side_effect=Exception)): with patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', Mock(side_effect=Exception)):
self.assertRaises(KubernetesError, self.k.get_cluster) self.assertRaises(KubernetesError, self.k.get_cluster)
@@ -50,6 +52,13 @@ class TestKubernetes(unittest.TestCase):
'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.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock())
def test_update_leader_with_restricted_access(self):
k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10,
'labels': {'f': 'b'}, 'use_endpoints': True, 'pod_ip': '10.0.0.0'})
self.assertIsNotNone(k.update_leader('123', True))
def test_take_leader(self): def test_take_leader(self):
self.k.take_leader() self.k.take_leader()
self.k._leader_observed_record['leader'] = 'test' self.k._leader_observed_record['leader'] = 'test'
@@ -65,7 +74,7 @@ class TestKubernetes(unittest.TestCase):
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', Mock(return_value=True)) @patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', Mock(return_value=True))
def test_touch_member(self): def test_touch_member(self):
self.k.touch_member({}) self.k.touch_member({'role': 'replica'})
self.k._name = 'p-1' self.k._name = 'p-1'
self.k.touch_member({'state': 'running', 'role': 'replica'}) self.k.touch_member({'state': 'running', 'role': 'replica'})
self.k.touch_member({'state': 'stopped', 'role': 'master'}) self.k.touch_member({'state': 'stopped', 'role': 'master'})
@@ -105,3 +114,15 @@ class TestKubernetes(unittest.TestCase):
def test_set_history_value(self): def test_set_history_value(self):
self.k.set_history_value('{}') self.k.set_history_value('{}')
@patch('kubernetes.config.load_kube_config', Mock())
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', Mock(return_value=True))
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', Mock())
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_service',
Mock(side_effect=[True, False, k8s_client.rest.ApiException(500, '')]))
def test__create_config_service(self):
k = Kubernetes({'ttl': 30, 'scope': 'test', 'name': 'p-0', 'retry_timeout': 10,
'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'}))
k.touch_member({'state': 'running', 'role': 'replica'})
+58
View File
@@ -0,0 +1,58 @@
import logging
import os
import sys
import unittest
import yaml
from mock import Mock, patch
from patroni.config import Config
from patroni.log import PatroniLogger
from six.moves.queue import Queue, Full
class TestPatroniLogger(unittest.TestCase):
def setUp(self):
self._handlers = logging.getLogger().handlers[:]
def tearDown(self):
logging.getLogger().handlers[:] = self._handlers
@patch('logging.FileHandler._open', Mock())
@patch('logging.Handler.close', Mock(side_effect=Exception))
def test_patroni_logger(self):
config = {
'log': {
'max_queue_size': 5,
'dir': 'foo',
'file_size': 4096,
'file_num': 5,
'loggers': {
'foo.bar': 'INFO'
}
},
'restapi': {}, 'postgresql': {'data_dir': 'foo'}
}
sys.argv = ['patroni.py']
os.environ[Config.PATRONI_CONFIG_VARIABLE] = yaml.dump(config, default_flow_style=False)
logger = PatroniLogger()
patroni_config = Config()
logger.reload_config(patroni_config['log'])
with patch.object(logging.Handler, 'format', Mock(side_effect=Exception)):
logging.error('test')
self.assertEqual(logger._log_handler.maxBytes, config['log']['file_size'])
self.assertEqual(logger._log_handler.backupCount, config['log']['file_num'])
config['log'].pop('dir')
logger.reload_config(config['log'])
with patch.object(logging.Logger, 'makeRecord',
Mock(side_effect=[logging.LogRecord('', logging.INFO, '', 0, '', (), None), Exception])):
logging.error('test')
logging.error('test')
with patch.object(Queue, 'put_nowait', Mock(side_effect=Full)):
self.assertRaises(SystemExit, logger.shutdown)
self.assertRaises(Exception, logger.shutdown)
self.assertLessEqual(logger.queue_size, 2) # "Failed to close the old log handler" could be still in the queue
self.assertEqual(logger.records_lost, 0)
+39 -16
View File
@@ -1,4 +1,6 @@
import etcd import etcd
import logging
import os
import signal import signal
import sys import sys
import time import time
@@ -9,10 +11,15 @@ from patroni.api import RestApiServer
from patroni.async_executor import AsyncExecutor from patroni.async_executor import AsyncExecutor
from patroni.dcs.etcd import Client from patroni.dcs.etcd import Client
from patroni.exceptions import DCSError from patroni.exceptions import DCSError
from patroni import Patroni, main as _main, patroni_main from patroni.postgresql import Postgresql
from six.moves import BaseHTTPServer from patroni.postgresql.config import ConfigHandler
from test_etcd import SleepException, etcd_read, etcd_write from patroni import Patroni, main as _main, patroni_main, check_psycopg2
from test_postgresql import Postgresql, psycopg2_connect, MockPostmaster from six.moves import BaseHTTPServer, builtins
from threading import Thread
from . import psycopg2_connect, SleepException
from .test_etcd import etcd_read, etcd_write
from .test_postgresql import MockPostmaster
class MockFrozenImporter(object): class MockFrozenImporter(object):
@@ -23,29 +30,36 @@ class MockFrozenImporter(object):
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
@patch('subprocess.call', Mock(return_value=0)) @patch('subprocess.call', Mock(return_value=0))
@patch('psycopg2.connect', psycopg2_connect) @patch('psycopg2.connect', psycopg2_connect)
@patch.object(Postgresql, 'write_pg_hba', Mock()) @patch.object(ConfigHandler, 'append_pg_hba', Mock())
@patch.object(Postgresql, '_write_postgresql_conf', Mock()) @patch.object(ConfigHandler, 'write_postgresql_conf', Mock())
@patch.object(Postgresql, 'write_recovery_conf', Mock()) @patch.object(ConfigHandler, 'write_recovery_conf', Mock())
@patch.object(Postgresql, 'is_running', Mock(return_value=MockPostmaster())) @patch.object(Postgresql, 'is_running', Mock(return_value=MockPostmaster()))
@patch.object(Postgresql, 'call_nowait', Mock()) @patch.object(Postgresql, 'call_nowait', Mock())
@patch.object(BaseHTTPServer.HTTPServer, '__init__', Mock()) @patch.object(BaseHTTPServer.HTTPServer, '__init__', Mock())
@patch.object(AsyncExecutor, 'run', Mock()) @patch.object(AsyncExecutor, 'run', Mock())
@patch.object(etcd.Client, 'write', etcd_write) @patch.object(etcd.Client, 'write', etcd_write)
@patch.object(etcd.Client, 'read', etcd_read) @patch.object(etcd.Client, 'read', etcd_read)
@patch.object(Thread, 'start', Mock())
class TestPatroni(unittest.TestCase): class TestPatroni(unittest.TestCase):
@patch('pkgutil.get_importer', Mock(return_value=MockFrozenImporter())) @patch('pkgutil.get_importer', 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(etcd.Client, 'read', etcd_read) @patch.object(etcd.Client, 'read', etcd_read)
def setUp(self): def setUp(self):
self._handlers = logging.getLogger().handlers[:]
RestApiServer._BaseServer__is_shut_down = Mock() RestApiServer._BaseServer__is_shut_down = Mock()
RestApiServer._BaseServer__shutdown_request = True RestApiServer._BaseServer__shutdown_request = True
RestApiServer.socket = 0 RestApiServer.socket = 0
with patch.object(Client, 'machines') as mock_machines: with patch.object(Client, 'machines') as mock_machines:
mock_machines.__get__ = Mock(return_value=['http://remotehost:2379']) mock_machines.__get__ = Mock(return_value=['http://remotehost:2379'])
sys.argv = ['patroni.py', 'postgres0.yml'] sys.argv = ['patroni.py', 'postgres0.yml']
os.environ['PATRONI_POSTGRESQL_DATA_DIR'] = 'data/test0'
self.p = Patroni() self.p = Patroni()
def tearDown(self):
logging.getLogger().handlers[:] = self._handlers
@patch('patroni.dcs.AbstractDCS.get_cluster', Mock(side_effect=[None, DCSError('foo'), None])) @patch('patroni.dcs.AbstractDCS.get_cluster', Mock(side_effect=[None, DCSError('foo'), None]))
def test_load_dynamic_configuration(self): def test_load_dynamic_configuration(self):
self.p.config._dynamic_configuration = {} self.p.config._dynamic_configuration = {}
@@ -55,6 +69,7 @@ class TestPatroni(unittest.TestCase):
@patch('time.sleep', Mock(side_effect=SleepException)) @patch('time.sleep', Mock(side_effect=SleepException))
@patch.object(etcd.Client, 'delete', Mock()) @patch.object(etcd.Client, 'delete', Mock())
@patch.object(Client, 'machines') @patch.object(Client, 'machines')
@patch.object(Thread, 'join', Mock())
def test_patroni_patroni_main(self, mock_machines): def test_patroni_patroni_main(self, mock_machines):
with patch('subprocess.call', Mock(return_value=1)): with patch('subprocess.call', Mock(return_value=1)):
sys.argv = ['patroni.py', 'postgres0.yml'] sys.argv = ['patroni.py', 'postgres0.yml']
@@ -67,16 +82,12 @@ class TestPatroni(unittest.TestCase):
patroni_main() patroni_main()
@patch('os.getpid') @patch('os.getpid')
@patch('subprocess.Popen', ) @patch('multiprocessing.Process')
@patch('patroni.patroni_main', Mock()) @patch('patroni.patroni_main', Mock())
def test_patroni_main(self, mock_popen, mock_getpid): def test_patroni_main(self, mock_process, mock_getpid):
mock_getpid.return_value = 2 mock_getpid.return_value = 2
_main() _main()
with patch('sys.frozen', Mock(return_value=True), create=True):
sys.argv = ['/patroni', 'pg_ctl_start', 'postgres', '-D', '/data', '--max_connections=100']
_main()
mock_getpid.return_value = 1 mock_getpid.return_value = 1
def mock_signal(signo, handler): def mock_signal(signo, handler):
@@ -91,18 +102,19 @@ class TestPatroni(unittest.TestCase):
ref = {'passtochild': lambda signo, stack_frame: 0} ref = {'passtochild': lambda signo, stack_frame: 0}
def mock_sighup(signo, handler): def mock_sighup(signo, handler):
if signo == signal.SIGHUP: if hasattr(signal, 'SIGHUP') and signo == signal.SIGHUP:
ref['passtochild'] = handler ref['passtochild'] = handler
def mock_wait(): def mock_join():
ref['passtochild'](0, None) ref['passtochild'](0, None)
mock_popen.return_value.wait = mock_wait mock_process.return_value.join = mock_join
with patch('signal.signal', mock_sighup), patch('os.kill', Mock()): with patch('signal.signal', mock_sighup), patch('os.kill', Mock()):
self.assertIsNone(_main()) self.assertIsNone(_main())
@patch('patroni.config.Config.save_cache', Mock()) @patch('patroni.config.Config.save_cache', Mock())
@patch('patroni.config.Config.reload_local_configuration', Mock(return_value=True)) @patch('patroni.config.Config.reload_local_configuration', Mock(return_value=True))
@patch('patroni.ha.Ha.is_leader', Mock(return_value=True))
@patch.object(Postgresql, 'state', PropertyMock(return_value='running')) @patch.object(Postgresql, 'state', PropertyMock(return_value='running'))
@patch.object(Postgresql, 'data_directory_empty', Mock(return_value=False)) @patch.object(Postgresql, 'data_directory_empty', Mock(return_value=False))
def test_run(self): def test_run(self):
@@ -121,6 +133,7 @@ class TestPatroni(unittest.TestCase):
self.assertRaises(SystemExit, self.p.sigterm_handler) self.assertRaises(SystemExit, self.p.sigterm_handler)
def test_schedule_next_run(self): def test_schedule_next_run(self):
self.p.ha.cluster = Mock()
self.p.ha.dcs.watch = Mock(return_value=True) self.p.ha.dcs.watch = Mock(return_value=True)
self.p.schedule_next_run() self.p.schedule_next_run()
self.p.next_run = time.time() - self.p.dcs.loop_wait - 1 self.p.next_run = time.time() - self.p.dcs.loop_wait - 1
@@ -151,3 +164,13 @@ class TestPatroni(unittest.TestCase):
self.assertTrue(self.p.nosync) self.assertTrue(self.p.nosync)
self.p.tags['nosync'] = None self.p.tags['nosync'] = None
self.assertFalse(self.p.nosync) self.assertFalse(self.p.nosync)
def test_shutdown(self):
self.p.api.shutdown = Mock(side_effect=Exception)
self.p.shutdown()
def test_check_psycopg2(self):
with patch.object(builtins, '__import__', Mock(side_effect=ImportError)):
self.assertRaises(SystemExit, check_psycopg2)
with patch('psycopg2.__version__', '2.5.3.dev1 a b c'):
self.assertRaises(SystemExit, check_psycopg2)
+172 -458
View File
@@ -1,113 +1,32 @@
import datetime
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 psycopg2 import psycopg2
import shutil
import subprocess import subprocess
import unittest 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, Leader, Member, SyncState from patroni.dcs import Cluster, ClusterConfig, Member, RemoteMember, SyncState
from patroni.exceptions import PostgresConnectionException, PostgresException from patroni.exceptions import PostgresConnectionException
from patroni.postgresql import Postgresql, STATE_REJECT, STATE_NO_RESPONSE from patroni.postgresql import Postgresql, STATE_REJECT, STATE_NO_RESPONSE
from patroni.postmaster import PostmasterProcess from patroni.postgresql.postmaster import PostmasterProcess
from patroni.postgresql.slots import SlotsHandler
from patroni.utils import RetryFailedError from patroni.utils import RetryFailedError
from six.moves import builtins from six.moves import builtins
from threading import Thread from threading import Thread, current_thread
from . import BaseTestPostgresql, MockCursor, MockPostmaster, psycopg2_connect
class MockCursor(object): mtime_ret = {}
def __init__(self, connection):
self.connection = connection
self.closed = False
self.rowcount = 0
self.results = []
def execute(self, sql, *params):
if sql.startswith('blabla'):
raise psycopg2.ProgrammingError()
elif sql == 'CHECKPOINT':
raise psycopg2.OperationalError()
elif sql.startswith('RetryFailedError'):
raise RetryFailedError('retry')
elif sql.startswith('SELECT slot_name'):
self.results = [('blabla',), ('foobar',)]
elif sql.startswith('SELECT CASE WHEN pg_is_in_recovery()'):
self.results = [(1, 2)]
elif sql.startswith('SELECT pg_is_in_recovery()'):
self.results = [(False, 2)]
elif sql.startswith('WITH replication_info AS ('):
replication_info = '[{"application_name":"walreceiver","client_addr":"1.2.3.4",' +\
'"state":"streaming","sync_state":"async","sync_priority":0}]'
self.results = [('', 0, '', '', '', '', False, replication_info)]
elif sql.startswith('SELECT name, setting'):
self.results = [('wal_segment_size', '2048', '8kB', 'integer', 'internal'),
('search_path', 'public', None, 'string', 'user'),
('port', '5433', None, 'integer', 'postmaster'),
('listen_addresses', '*', None, 'string', 'postmaster'),
('autovacuum', 'on', None, 'bool', 'sighup'),
('unix_socket_directories', '/tmp', None, 'string', 'postmaster')]
elif sql.startswith('IDENTIFY_SYSTEM'):
self.results = [('1', 2, '0/402EEC0', '')]
elif sql.startswith('SELECT isdir, modification'):
self.results = [(False, datetime.datetime.now())]
elif sql.startswith('SELECT pg_read_file'):
self.results = [('1\t0/40159C0\tno recovery target specified\n\n' +
'2\t1/40159C0\tno recovery target specified\n',)]
elif sql.startswith('TIMELINE_HISTORY '):
self.results = [('', b'x\t0/40159C0\tno recovery target specified\n\n' +
b'1\t0/40159C0\tno recovery target specified\n\n' +
b'2\t0/402DD98\tno recovery target specified\n\n' +
b'3\t0/403DD98\tno recovery target specified\n')]
else:
self.results = [(None, None, None, None, None, None, None, None, None, None)]
def fetchone(self):
return self.results[0]
def fetchall(self):
return self.results
def __iter__(self):
for i in self.results:
yield i
def __enter__(self):
return self
def __exit__(self, *args):
pass
class MockConnect(object): def mock_mtime(filename):
if filename not in mtime_ret:
server_version = 99999 mtime_ret[filename] = time.time()
autocommit = False else:
closed = 0 mtime_ret[filename] += 1
return mtime_ret[filename]
def cursor(self):
return MockCursor(self)
def __enter__(self):
return self
def __exit__(self, *args):
pass
@staticmethod
def close():
pass
class MockPostmaster(object):
def __init__(self, is_running=True, is_single_master=False):
self.is_running = Mock(return_value=is_running)
self.is_single_master = Mock(return_value=is_single_master)
self.wait_for_user_backends_to_close = Mock()
self.signal_stop = Mock(return_value=None)
self.wait = Mock()
def pg_controldata_string(*args, **kwargs): def pg_controldata_string(*args, **kwargs):
@@ -165,62 +84,18 @@ Data page checksum version: 0
""" """
def psycopg2_connect(*args, **kwargs):
return MockConnect()
@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 TestPostgresql(unittest.TestCase): class TestPostgresql(BaseTestPostgresql):
_PARAMETERS = {'wal_level': 'hot_standby', 'max_replication_slots': 5, 'f.oo': 'bar',
'search_path': 'public', 'hot_standby': 'on', 'max_wal_senders': 5,
'wal_keep_segments': 8, 'wal_log_hints': 'on', 'max_locks_per_transaction': 64,
'max_worker_processes': 8, 'max_connections': 100, 'max_prepared_transactions': 0,
'track_commit_timestamp': 'off', 'unix_socket_directories': '/tmp'}
@patch('subprocess.call', Mock(return_value=0)) @patch('subprocess.call', Mock(return_value=0))
@patch('psycopg2.connect', psycopg2_connect)
@patch('os.rename', Mock()) @patch('os.rename', Mock())
@patch.object(Postgresql, 'get_major_version', Mock(return_value=90600)) @patch.object(Postgresql, 'get_major_version', Mock(return_value=120000))
@patch.object(Postgresql, 'is_running', Mock(return_value=True)) @patch.object(Postgresql, 'is_running', Mock(return_value=True))
def setUp(self): def setUp(self):
self.data_dir = 'data/test0' super(TestPostgresql, self).setUp()
self.config_dir = self.data_dir self.p.config.write_postgresql_conf()
if not os.path.exists(self.data_dir):
os.makedirs(self.data_dir)
self.p = Postgresql({'name': 'test0', 'scope': 'batman', 'data_dir': self.data_dir,
'config_dir': self.config_dir, 'retry_timeout': 10, 'pgpass': '/tmp/pgpass0',
'listen': '127.0.0.2, 127.0.0.3:5432', 'connect_address': '127.0.0.2:5432',
'authentication': {'superuser': {'username': 'test', 'password': 'test'},
'replication': {'username': 'replicator', 'password': 'rep-pass'}},
'remove_data_directory_on_rewind_failure': True,
'use_pg_rewind': True, 'pg_ctl_timeout': 'bla',
'parameters': self._PARAMETERS,
'recovery_conf': {'foo': 'bar'},
'pg_hba': ['host all all 0.0.0.0/0 md5'],
'callbacks': {'on_start': 'true', 'on_stop': 'true', 'on_reload': 'true',
'on_restart': 'true', 'on_role_change': 'true'}})
self.p._callback_executor = Mock() self.p._callback_executor = Mock()
self.leadermem = Member(0, 'leader', 28, {'conn_url': 'postgres://replicator:[email protected]:5435/postgres'})
self.leader = Leader(-1, 28, self.leadermem)
self.other = Member(0, 'test-1', 28, {'conn_url': 'postgres://replicator:[email protected]:5433/postgres',
'tags': {'replicatefrom': 'leader'}})
self.me = Member(0, 'test0', 28, {'conn_url': 'postgres://replicator:[email protected]:5434/postgres'})
def tearDown(self):
shutil.rmtree('data')
def test_get_initdb_options(self):
self.assertEquals(self.p.get_initdb_options([{'encoding': 'UTF8'}, 'data-checksums']),
['--encoding=UTF8', '--data-checksums'])
self.assertRaises(Exception, self.p.get_initdb_options, [{'pgdata': 'bar'}])
self.assertRaises(Exception, self.p.get_initdb_options, [{'foo': 'bar', 1: 2}])
self.assertRaises(Exception, self.p.get_initdb_options, [1])
@patch('os.path.exists', Mock(return_value=True))
@patch('os.unlink', Mock())
def test_delete_trigger_file(self):
self.p.delete_trigger_file()
@patch('subprocess.Popen') @patch('subprocess.Popen')
@patch.object(Postgresql, 'wait_for_startup') @patch.object(Postgresql, 'wait_for_startup')
@@ -236,7 +111,7 @@ class TestPostgresql(unittest.TestCase):
mock_postmaster = MockPostmaster() mock_postmaster = MockPostmaster()
with patch.object(PostmasterProcess, 'start', return_value=mock_postmaster): with patch.object(PostmasterProcess, 'start', return_value=mock_postmaster):
pg_conf = os.path.join(self.data_dir, 'postgresql.conf') pg_conf = os.path.join(self.p.data_dir, 'postgresql.conf')
open(pg_conf, 'w').close() open(pg_conf, 'w').close()
self.assertFalse(self.p.start(task=CriticalTask())) self.assertFalse(self.p.start(task=CriticalTask()))
@@ -254,7 +129,7 @@ class TestPostgresql(unittest.TestCase):
task.cancel() task.cancel()
self.assertFalse(self.p.start(task=task)) self.assertFalse(self.p.start(task=task))
self.p.cancel() self.p.cancellable.cancel()
self.assertFalse(self.p.start()) self.assertFalse(self.p.start())
@patch.object(Postgresql, 'pg_isready') @patch.object(Postgresql, 'pg_isready')
@@ -276,7 +151,7 @@ class TestPostgresql(unittest.TestCase):
self.assertTrue(self.p.wait_for_port_open(mock_postmaster, 1)) self.assertTrue(self.p.wait_for_port_open(mock_postmaster, 1))
# cancelled # cancelled
self.p.cancel() self.p.cancellable.cancel()
self.assertFalse(self.p.wait_for_port_open(mock_postmaster, 1)) self.assertFalse(self.p.wait_for_port_open(mock_postmaster, 1))
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
@@ -309,7 +184,7 @@ class TestPostgresql(unittest.TestCase):
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())
self.assertEquals(self.p.state, 'restart failed (restarting)') self.assertEqual(self.p.state, 'restart failed (restarting)')
@patch.object(builtins, 'open', MagicMock()) @patch.object(builtins, 'open', MagicMock())
def test_write_pgpass(self): def test_write_pgpass(self):
@@ -318,153 +193,92 @@ class TestPostgresql(unittest.TestCase):
def test_checkpoint(self): def test_checkpoint(self):
with patch.object(MockCursor, 'fetchone', Mock(return_value=(True, ))): with patch.object(MockCursor, 'fetchone', Mock(return_value=(True, ))):
self.assertEquals(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.assertEquals(self.p.checkpoint(), 'not accessible or not healty') self.assertEqual(self.p.checkpoint(), 'not accessible or not healty')
@patch.object(Postgresql, 'cancellable_subprocess_call')
@patch('patroni.postgresql.Postgresql.write_pgpass', MagicMock(return_value=dict()))
def test_pg_rewind(self, mock_cancellable_subprocess_call):
r = {'user': '', 'host': '', 'port': '', 'database': '', 'password': ''}
mock_cancellable_subprocess_call.return_value = 0
self.assertTrue(self.p.pg_rewind(r))
mock_cancellable_subprocess_call.side_effect = OSError
self.assertFalse(self.p.pg_rewind(r))
@patch('patroni.postgresql.config.mtime', mock_mtime)
@patch.object(MockCursor, 'fetchone', Mock(side_effect=[('foo=bar',), ('',), ('',), ('a=b',)]))
def test_check_recovery_conf(self): def test_check_recovery_conf(self):
self.p.write_recovery_conf({'primary_conninfo': 'foo'}) for version in (120000, 100000):
self.assertFalse(self.p.check_recovery_conf(None)) with patch.object(Postgresql, 'major_version', PropertyMock(return_value=version)):
self.p.write_recovery_conf({}) self.p.config.write_recovery_conf({'standby_mode': 'on', 'primary_conninfo': 'foo'})
self.assertTrue(self.p.check_recovery_conf(None)) self.assertFalse(self.p.config.check_recovery_conf(None))
self.p.config.write_recovery_conf({'primary_conninfo': 'foo'})
self.p.config.write_postgresql_conf()
self.assertFalse(self.p.config.check_recovery_conf(None))
self.p.config.write_recovery_conf({'standby_mode': 'on'})
self.assertTrue(self.p.config.check_recovery_conf(None))
with patch('patroni.postgresql.config.ConfigHandler.primary_conninfo_params',
Mock(return_value={'a': 'b'})):
self.assertFalse(self.p.config.check_recovery_conf(None))
self.p.config.write_recovery_conf({'standby_mode': 'on', 'primary_conninfo': 'a=b'})
self.assertTrue(self.p.config.check_recovery_conf(None))
@patch.object(Postgresql, 'start', Mock()) @patch.object(Postgresql, 'major_version', PropertyMock(return_value=120000))
@patch.object(Postgresql, 'can_rewind', PropertyMock(return_value=True)) @patch.object(Postgresql, 'is_running', MockPostmaster)
def test__get_local_timeline_lsn(self): @patch.object(MockPostmaster, 'create_time', Mock(return_value=1234567), create=True)
self.p.trigger_check_diverged_lsn() @patch.object(MockCursor, 'fetchone', Mock(return_value=('',)))
with patch.object(Postgresql, 'controldata', def test__read_primary_conninfo(self):
Mock(return_value={'Database cluster state': 'shut down in recovery', self.p.config.write_recovery_conf({'standby_mode': 'on'})
'Minimum recovery ending location': '0/0', self.p.config.write_postgresql_conf()
"Min recovery ending loc's timeline": '0'})): self.assertTrue(self.p.config.check_recovery_conf(None))
self.p.rewind_needed_and_possible(self.leader) self.assertTrue(self.p.config.check_recovery_conf(None))
with patch.object(Postgresql, 'is_running', Mock(return_value=True)): with patch.object(Postgresql, 'query', Mock(side_effect=Exception)),\
with patch.object(MockCursor, 'fetchone', Mock(side_effect=[(False, ), Exception])): patch('patroni.postgresql.config.mtime', mock_mtime):
self.p.rewind_needed_and_possible(self.leader) self.assertFalse(self.p.config.check_recovery_conf(None))
@patch.object(Postgresql, 'start', Mock()) @patch.object(Postgresql, 'major_version', PropertyMock(return_value=100000))
@patch.object(Postgresql, 'can_rewind', PropertyMock(return_value=True)) def test__read_primary_conninfo_pre_v12(self):
@patch.object(Postgresql, '_get_local_timeline_lsn', Mock(return_value=(2, '40159C1'))) self.p.config.write_recovery_conf({'standby_mode': 'on'})
@patch.object(Postgresql, 'check_leader_is_not_in_recovery') self.assertTrue(self.p.config.check_recovery_conf(None))
def test__check_timeline_and_lsn(self, mock_check_leader_is_not_in_recovery): self.assertTrue(self.p.config.check_recovery_conf(None))
mock_check_leader_is_not_in_recovery.return_value = False
self.p.trigger_check_diverged_lsn()
self.assertFalse(self.p.rewind_needed_and_possible(self.leader))
mock_check_leader_is_not_in_recovery.return_value = True
self.assertFalse(self.p.rewind_needed_and_possible(self.leader))
self.p.trigger_check_diverged_lsn()
with patch('psycopg2.connect', Mock(side_effect=Exception)):
self.assertFalse(self.p.rewind_needed_and_possible(self.leader))
self.p.trigger_check_diverged_lsn()
with patch.object(MockCursor, 'fetchone', Mock(side_effect=[('', 2, '0/0'), ('', b'3\t0/40159C0\tn\n')])):
self.assertFalse(self.p.rewind_needed_and_possible(self.leader))
self.p.trigger_check_diverged_lsn()
with patch.object(MockCursor, 'fetchone', Mock(return_value=('', 1, '0/0'))):
with patch.object(Postgresql, '_get_local_timeline_lsn', Mock(return_value=(1, '0/0'))):
self.assertFalse(self.p.rewind_needed_and_possible(self.leader))
self.p.trigger_check_diverged_lsn()
self.assertTrue(self.p.rewind_needed_and_possible(self.leader))
@patch.object(MockCursor, 'fetchone', Mock(side_effect=[(True,), Exception])) def test_write_postgresql_and_sanitize_auto_conf(self):
def test_check_leader_is_not_in_recovery(self): read_data = 'primary_conninfo = foo\nfoo = bar\n'
self.p.check_leader_is_not_in_recovery() with open(os.path.join(self.p.data_dir, 'postgresql.auto.conf'), 'w') as f:
self.p.check_leader_is_not_in_recovery() f.write(read_data)
@patch.object(Postgresql, 'cancellable_subprocess_call', Mock(return_value=0)) mock_read_auto = mock_open(read_data=read_data)
@patch.object(Postgresql, 'checkpoint', side_effect=['', '1']) mock_read_auto.return_value.__iter__ = lambda o: iter(o.readline, '')
@patch.object(Postgresql, 'stop', Mock(return_value=False)) with patch.object(builtins, 'open', Mock(side_effect=[mock_open()(), mock_read_auto(), IOError])),\
@patch.object(Postgresql, 'start', Mock()) patch('os.chmod', Mock()):
def test_rewind(self, mock_checkpoint): self.p.config.write_postgresql_conf()
self.p.rewind(self.leader)
with patch.object(Postgresql, 'pg_rewind', Mock(return_value=False)): with patch.object(builtins, 'open', Mock(side_effect=[mock_open()(), IOError])), patch('os.chmod', Mock()):
mock_checkpoint.side_effect = ['1', '', '', ''] self.p.config.write_postgresql_conf()
self.p.rewind(self.leader) self.p.config.write_recovery_conf({'foo': 'bar'})
self.p.rewind(self.leader) self.p.config.write_postgresql_conf()
with patch.object(Postgresql, 'check_leader_is_not_in_recovery', Mock(return_value=False)):
self.p.rewind(self.leader)
self.p.config['remove_data_directory_on_rewind_failure'] = False
self.p.trigger_check_diverged_lsn()
self.p.rewind(self.leader)
with patch.object(Postgresql, 'is_running', Mock(return_value=True)):
self.p.rewind(self.leader)
self.p.is_leader = Mock(return_value=False)
self.p.rewind(self.leader)
@patch.object(Postgresql, 'is_running', Mock(return_value=False)) @patch.object(Postgresql, 'is_running', Mock(return_value=False))
@patch.object(Postgresql, 'start', Mock()) @patch.object(Postgresql, 'start', Mock())
def test_follow(self): def test_follow(self):
self.p.follow(None) self.p.call_nowait('on_start')
m = RemoteMember('1', {'restore_command': '2', 'recovery_min_apply_delay': 3, 'archive_cleanup_command': '4'})
@patch('subprocess.check_output', Mock(return_value=0, side_effect=pg_controldata_string)) self.p.follow(m)
def test_can_rewind(self):
with patch('subprocess.call', MagicMock(return_value=1)):
self.assertFalse(self.p.can_rewind)
with patch('subprocess.call', side_effect=OSError):
self.assertFalse(self.p.can_rewind)
with patch.object(Postgresql, 'controldata', Mock(return_value={'wal_log_hints setting': 'on'})):
self.assertTrue(self.p.can_rewind)
self.p.config['use_pg_rewind'] = False
self.assertFalse(self.p.can_rewind)
@patch('time.sleep', Mock())
@patch.object(Postgresql, 'cancellable_subprocess_call')
@patch.object(Postgresql, 'remove_data_directory', Mock(return_value=True))
def test_create_replica(self, mock_cancellable_subprocess_call):
self.p.delete_trigger_file = Mock(side_effect=OSError)
self.p.config['create_replica_method'] = ['wale', 'basebackup']
self.p.config['wale'] = {'command': 'foo'}
mock_cancellable_subprocess_call.return_value = 0
self.assertEquals(self.p.create_replica(self.leader), 0)
del self.p.config['wale']
self.assertEquals(self.p.create_replica(self.leader), 0)
mock_cancellable_subprocess_call.return_value = 1
self.assertEquals(self.p.create_replica(self.leader), 1)
mock_cancellable_subprocess_call.side_effect = Exception('foo')
self.assertEquals(self.p.create_replica(self.leader), 1)
mock_cancellable_subprocess_call.side_effect = [1, 0]
self.assertEquals(self.p.create_replica(self.leader), 0)
mock_cancellable_subprocess_call.side_effect = [Exception(), 0]
self.assertEquals(self.p.create_replica(self.leader), 0)
self.p.cancel()
self.assertEquals(self.p.create_replica(self.leader), 1)
def test_basebackup(self):
self.p.cancel()
self.p.basebackup(None, None)
@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()
cluster = Cluster(True, None, self.leader, 0, [self.me, self.other, self.leadermem], None, None, None) config = ClusterConfig(1, {'slots': {'ls': {'database': 'a', 'plugin': 'b'},
'A': 0, 'test_3': 0, 'b': {'type': 'logical', 'plugin': '1'}}}, 1)
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.sync_replication_slots(cluster) self.p.slots_handler.sync_replication_slots(cluster)
self.p.sync_replication_slots(cluster) self.p.slots_handler.sync_replication_slots(cluster)
with mock.patch('patroni.postgresql.Postgresql.role', new_callable=PropertyMock(return_value='replica')): with mock.patch('patroni.postgresql.Postgresql.role', new_callable=PropertyMock(return_value='replica')):
self.p.sync_replication_slots(cluster) self.p.slots_handler.sync_replication_slots(cluster)
with mock.patch('patroni.postgresql.logger.error', new_callable=Mock()) as errorlog_mock: with patch.object(SlotsHandler, 'drop_replication_slot', Mock(return_value=True)),\
self.p.query = Mock() patch('patroni.dcs.logger.error', new_callable=Mock()) as errorlog_mock:
alias1 = Member(0, 'test-3', 28, {'conn_url': 'postgres://replicator:[email protected]:5436/postgres'}) alias1 = Member(0, 'test-3', 28, {'conn_url': 'postgres://replicator:[email protected]:5436/postgres'})
alias2 = Member(0, 'test.3', 28, {'conn_url': 'postgres://replicator:[email protected]:5436/postgres'}) alias2 = Member(0, 'test.3', 28, {'conn_url': 'postgres://replicator:[email protected]:5436/postgres'})
cluster.members.extend([alias1, alias2]) cluster.members.extend([alias1, alias2])
self.p.sync_replication_slots(cluster) self.p.slots_handler.sync_replication_slots(cluster)
errorlog_mock.assert_called_once() self.assertEqual(errorlog_mock.call_count, 5)
assert "test-3" in errorlog_mock.call_args[0][1] ca = errorlog_mock.call_args_list[0][0][1]
assert "test.3" in errorlog_mock.call_args[0][1] self.assertTrue("test-3" in ca, "non matching {0}".format(ca))
self.assertTrue("test.3" in ca, "non matching {0}".format(ca))
@patch.object(MockCursor, 'execute', Mock(side_effect=psycopg2.OperationalError)) @patch.object(MockCursor, 'execute', Mock(side_effect=psycopg2.OperationalError))
def test__query(self): def test__query(self):
@@ -500,25 +314,25 @@ class TestPostgresql(unittest.TestCase):
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.assertEquals(self.p.timeline_wal_position(), (1, 2)) self.assertEqual(self.p.timeline_wal_position(), (1, 2))
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')
def test_is_running(self, mock_frompidfile): def test_is_running(self, mock_frompidfile):
# Cached postmaster running # Cached postmaster running
mock_postmaster = self.p._postmaster_proc = MockPostmaster() mock_postmaster = self.p._postmaster_proc = MockPostmaster()
self.assertEquals(self.p.is_running(), mock_postmaster) self.assertEqual(self.p.is_running(), mock_postmaster)
# Cached postmaster not running, no postmaster running # Cached postmaster not running, no postmaster running
mock_postmaster.is_running.return_value = False mock_postmaster.is_running.return_value = False
mock_frompidfile.return_value = None mock_frompidfile.return_value = None
self.assertEquals(self.p.is_running(), None) self.assertEqual(self.p.is_running(), None)
self.assertEquals(self.p._postmaster_proc, None) self.assertEqual(self.p._postmaster_proc, None)
# No cached postmaster, postmaster running # No cached postmaster, postmaster running
mock_frompidfile.return_value = mock_postmaster2 = MockPostmaster() mock_frompidfile.return_value = mock_postmaster2 = MockPostmaster()
self.assertEquals(self.p.is_running(), mock_postmaster2) self.assertEqual(self.p.is_running(), mock_postmaster2)
self.assertEquals(self.p._postmaster_proc, mock_postmaster2) self.assertEqual(self.p._postmaster_proc, mock_postmaster2)
@patch('shlex.split', Mock(side_effect=OSError)) @patch('shlex.split', Mock(side_effect=OSError))
def test_call_nowait(self): def test_call_nowait(self):
@@ -543,118 +357,24 @@ class TestPostgresql(unittest.TestCase):
with patch('os.rename', Mock(side_effect=OSError)): with patch('os.rename', Mock(side_effect=OSError)):
self.p.move_data_directory() self.p.move_data_directory()
@patch.object(Postgresql, 'is_running', Mock(return_value=True))
def test_bootstrap(self):
with patch('subprocess.call', Mock(return_value=1)):
self.assertFalse(self.p.bootstrap({}))
config = {'users': {'replicator': {'password': 'rep-pass', 'options': ['replication']}}}
self.p.bootstrap(config)
with open(os.path.join(self.config_dir, 'pg_hba.conf')) as f:
lines = f.readlines()
self.assertTrue('host all all 0.0.0.0/0 md5\n' in lines)
self.p.config.pop('pg_hba')
config.update({'post_init': '/bin/false',
'pg_hba': ['host replication replicator 127.0.0.1/32 md5',
'hostssl all all 0.0.0.0/0 md5',
'host all all 0.0.0.0/0 md5']})
self.p.bootstrap(config)
with open(os.path.join(self.data_dir, 'pg_hba.conf')) as f:
lines = f.readlines()
self.assertTrue('host replication replicator 127.0.0.1/32 md5\n' in lines)
@patch.object(Postgresql, 'cancellable_subprocess_call')
def test_custom_bootstrap(self, mock_cancellable_subprocess_call):
config = {'method': 'foo', 'foo': {'command': 'bar'}}
mock_cancellable_subprocess_call.return_value = 1
self.assertFalse(self.p.bootstrap(config))
mock_cancellable_subprocess_call.return_value = 0
with patch('subprocess.Popen', Mock(side_effect=Exception("42"))),\
patch('os.path.isfile', Mock(return_value=True)),\
patch('os.unlink', Mock()),\
patch.object(Postgresql, 'save_configuration_files', Mock()),\
patch.object(Postgresql, 'restore_configuration_files', Mock()),\
patch.object(Postgresql, 'write_recovery_conf', Mock()):
with self.assertRaises(Exception) as e:
self.p.bootstrap(config)
self.assertEqual(str(e.exception), '42')
config['foo']['recovery_conf'] = {'foo': 'bar'}
with self.assertRaises(Exception) as e:
self.p.bootstrap(config)
self.assertEqual(str(e.exception), '42')
mock_cancellable_subprocess_call.side_effect = Exception
self.assertFalse(self.p.bootstrap(config))
@patch('time.sleep', Mock())
@patch('os.unlink', Mock())
@patch.object(Postgresql, 'run_bootstrap_post_init', Mock(return_value=True))
@patch.object(Postgresql, '_custom_bootstrap', Mock(return_value=True))
@patch.object(Postgresql, 'start', Mock(return_value=True))
def test_post_bootstrap(self):
config = {'method': 'foo', 'foo': {'command': 'bar'}}
self.p.bootstrap(config)
task = CriticalTask()
with patch.object(Postgresql, 'create_or_update_role', Mock(side_effect=Exception)):
self.p.post_bootstrap({}, task)
self.assertFalse(task.result)
self.p.config.pop('pg_hba')
self.p.post_bootstrap({}, task)
self.assertTrue(task.result)
self.p.bootstrap(config)
self.p.set_state('stopped')
self.p.reload_config({'authentication': {'superuser': {'username': 'p', 'password': 'p'},
'replication': {'username': 'r', 'password': 'r'}},
'listen': '*', 'retry_timeout': 10, 'parameters': {'hba_file': 'foo'}})
with patch.object(Postgresql, 'restart', Mock()) as mock_restart:
self.p.post_bootstrap({}, task)
mock_restart.assert_called_once()
@patch.object(Postgresql, 'cancellable_subprocess_call')
def test_run_bootstrap_post_init(self, mock_cancellable_subprocess_call):
mock_cancellable_subprocess_call.return_value = 1
self.assertFalse(self.p.run_bootstrap_post_init({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.return_value = 0
self.p._superuser.pop('username')
self.assertTrue(self.p.run_bootstrap_post_init({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.assert_called()
args, kwargs = mock_cancellable_subprocess_call.call_args
self.assertTrue('PGPASSFILE' in kwargs['env'])
self.assertEquals(args[0], ['/bin/false', 'postgres://127.0.0.2:5432/postgres'])
mock_cancellable_subprocess_call.reset_mock()
self.p._local_address.pop('host')
self.assertTrue(self.p.run_bootstrap_post_init({'post_init': '/bin/false'}))
mock_cancellable_subprocess_call.assert_called()
self.assertEquals(mock_cancellable_subprocess_call.call_args[0][0], ['/bin/false', 'postgres://:5432/postgres'])
mock_cancellable_subprocess_call.side_effect = OSError
self.assertFalse(self.p.run_bootstrap_post_init({'post_init': '/bin/false'}))
@patch('patroni.postgresql.Postgresql.create_replica', Mock(return_value=0))
def test_clone(self):
self.p.clone(self.leader)
@patch('os.listdir', Mock(return_value=['recovery.conf'])) @patch('os.listdir', Mock(return_value=['recovery.conf']))
@patch('os.path.exists', Mock(return_value=True)) @patch('os.path.exists', Mock(return_value=True))
def test_get_postgres_role_from_data_directory(self): def test_get_postgres_role_from_data_directory(self):
self.assertEquals(self.p.get_postgres_role_from_data_directory(), 'replica') self.assertEqual(self.p.get_postgres_role_from_data_directory(), 'replica')
def test_remove_data_directory(self): def test_remove_data_directory(self):
def _symlink(src, dst):
try:
os.symlink(src, dst)
except OSError:
if os.name == 'nt': # os.symlink under Windows needs admin rights skip it
pass
os.makedirs(os.path.join(self.p.data_dir, 'foo'))
_symlink('foo', os.path.join(self.p.data_dir, 'pg_wal'))
self.p.remove_data_directory() self.p.remove_data_directory()
open(self.data_dir, 'w').close() open(self.p.data_dir, 'w').close()
self.p.remove_data_directory() self.p.remove_data_directory()
os.symlink('unexisting', self.data_dir) _symlink('unexisting', self.p.data_dir)
with patch('os.unlink', Mock(side_effect=OSError)): with patch('os.unlink', Mock(side_effect=OSError)):
self.p.remove_data_directory() self.p.remove_data_directory()
self.p.remove_data_directory() self.p.remove_data_directory()
@@ -663,13 +383,13 @@ class TestPostgresql(unittest.TestCase):
def test_controldata(self): def test_controldata(self):
with patch('subprocess.check_output', Mock(return_value=0, side_effect=pg_controldata_string)): with patch('subprocess.check_output', Mock(return_value=0, side_effect=pg_controldata_string)):
data = self.p.controldata() data = self.p.controldata()
self.assertEquals(len(data), 50) self.assertEqual(len(data), 50)
self.assertEquals(data['Database cluster state'], 'shut down in recovery') self.assertEqual(data['Database cluster state'], 'shut down in recovery')
self.assertEquals(data['wal_log_hints setting'], 'on') self.assertEqual(data['wal_log_hints setting'], 'on')
self.assertEquals(int(data['Database block size']), 8192) self.assertEqual(int(data['Database block size']), 8192)
with patch('subprocess.check_output', Mock(side_effect=subprocess.CalledProcessError(1, ''))): with patch('subprocess.check_output', Mock(side_effect=subprocess.CalledProcessError(1, ''))):
self.assertEquals(self.p.controldata(), {}) self.assertEqual(self.p.controldata(), {})
@patch('patroni.postgresql.Postgresql._version_file_exists', Mock(return_value=True)) @patch('patroni.postgresql.Postgresql._version_file_exists', Mock(return_value=True))
@patch('subprocess.check_output', MagicMock(return_value=0, side_effect=pg_controldata_string)) @patch('subprocess.check_output', MagicMock(return_value=0, side_effect=pg_controldata_string))
@@ -679,34 +399,34 @@ class TestPostgresql(unittest.TestCase):
@patch('os.path.isfile', Mock(return_value=True)) @patch('os.path.isfile', Mock(return_value=True))
@patch('shutil.copy', Mock(side_effect=IOError)) @patch('shutil.copy', Mock(side_effect=IOError))
def test_save_configuration_files(self): def test_save_configuration_files(self):
self.p.save_configuration_files() self.p.config.save_configuration_files()
@patch('os.path.isfile', Mock(side_effect=[False, True])) @patch('os.path.isfile', Mock(side_effect=[False, True]))
@patch('shutil.copy', Mock(side_effect=IOError)) @patch('shutil.copy', Mock(side_effect=IOError))
def test_restore_configuration_files(self): def test_restore_configuration_files(self):
self.p.restore_configuration_files() self.p.config.restore_configuration_files()
def test_can_create_replica_without_replication_connection(self): def test_can_create_replica_without_replication_connection(self):
self.p.config['create_replica_method'] = [] self.p.config._config['create_replica_method'] = []
self.assertFalse(self.p.can_create_replica_without_replication_connection()) self.assertFalse(self.p.can_create_replica_without_replication_connection())
self.p.config['create_replica_method'] = ['wale', 'basebackup'] self.p.config._config['create_replica_method'] = ['wale', 'basebackup']
self.p.config['wale'] = {'command': 'foo', 'no_master': 1} self.p.config._config['wale'] = {'command': 'foo', 'no_master': 1}
self.assertTrue(self.p.can_create_replica_without_replication_connection()) self.assertTrue(self.p.can_create_replica_without_replication_connection())
def test_replica_method_can_work_without_replication_connection(self): def test_replica_method_can_work_without_replication_connection(self):
self.assertFalse(self.p.replica_method_can_work_without_replication_connection('basebackup')) self.assertFalse(self.p.replica_method_can_work_without_replication_connection('basebackup'))
self.assertFalse(self.p.replica_method_can_work_without_replication_connection('foobar')) self.assertFalse(self.p.replica_method_can_work_without_replication_connection('foobar'))
self.p.config['foo'] = {'command': 'bar', 'no_master': 1} self.p.config._config['foo'] = {'command': 'bar', 'no_master': 1}
self.assertTrue(self.p.replica_method_can_work_without_replication_connection('foo')) self.assertTrue(self.p.replica_method_can_work_without_replication_connection('foo'))
self.p.config['foo'] = {'command': 'bar'} self.p.config._config['foo'] = {'command': 'bar'}
self.assertFalse(self.p.replica_method_can_work_without_replication_connection('foo')) self.assertFalse(self.p.replica_method_can_work_without_replication_connection('foo'))
@patch.object(Postgresql, 'is_running', Mock(return_value=True)) @patch.object(Postgresql, 'is_running', Mock(return_value=True))
def test_reload_config(self): def test_reload_config(self):
parameters = self._PARAMETERS.copy() parameters = self._PARAMETERS.copy()
parameters.pop('f.oo') parameters.pop('f.oo')
config = {'pg_hba': [''], 'use_unix_socket': True, 'authentication': {}, config = {'pg_hba': [''], 'pg_ident': [''], 'use_unix_socket': True, 'authentication': {},
'retry_timeout': 10, 'listen': '*', 'parameters': parameters} 'retry_timeout': 10, 'listen': '*', 'krbsrvname': 'postgres', 'parameters': parameters}
self.p.reload_config(config) self.p.reload_config(config)
parameters['b.ar'] = 'bar' parameters['b.ar'] = 'bar'
self.p.reload_config(config) self.p.reload_config(config)
@@ -718,14 +438,14 @@ class TestPostgresql(unittest.TestCase):
self.p.reload_config(config) self.p.reload_config(config)
parameters['unix_socket_directories'] = '.' parameters['unix_socket_directories'] = '.'
self.p.reload_config(config) self.p.reload_config(config)
self.p.resolve_connection_addresses() self.p.config.resolve_connection_addresses()
@patch.object(Postgresql, '_version_file_exists', Mock(return_value=True)) @patch.object(Postgresql, '_version_file_exists', Mock(return_value=True))
def test_get_major_version(self): def test_get_major_version(self):
with patch.object(builtins, 'open', mock_open(read_data='9.4')): with patch.object(builtins, 'open', mock_open(read_data='9.4')):
self.assertEquals(self.p.get_major_version(), 90400) self.assertEqual(self.p.get_major_version(), 90400)
with patch.object(builtins, 'open', Mock(side_effect=Exception)): with patch.object(builtins, 'open', Mock(side_effect=Exception)):
self.assertEquals(self.p.get_major_version(), 0) self.assertEqual(self.p.get_major_version(), 0)
def test_postmaster_start_time(self): def test_postmaster_start_time(self):
with patch.object(MockCursor, "fetchone", Mock(return_value=('foo', True, '', '', '', '', False))): with patch.object(MockCursor, "fetchone", Mock(return_value=('foo', True, '', '', '', '', False))):
@@ -737,38 +457,40 @@ class TestPostgresql(unittest.TestCase):
with patch('subprocess.call', return_value=0): with patch('subprocess.call', return_value=0):
self.p._state = 'starting' self.p._state = 'starting'
self.assertFalse(self.p.check_for_startup()) self.assertFalse(self.p.check_for_startup())
self.assertEquals(self.p.state, 'running') self.assertEqual(self.p.state, 'running')
with patch('subprocess.call', return_value=1): with patch('subprocess.call', return_value=1):
self.p._state = 'starting' self.p._state = 'starting'
self.assertTrue(self.p.check_for_startup()) self.assertTrue(self.p.check_for_startup())
self.assertEquals(self.p.state, 'starting') self.assertEqual(self.p.state, 'starting')
with patch('subprocess.call', return_value=2): with patch('subprocess.call', return_value=2):
self.p._state = 'starting' self.p._state = 'starting'
self.assertFalse(self.p.check_for_startup()) self.assertFalse(self.p.check_for_startup())
self.assertEquals(self.p.state, 'start failed') self.assertEqual(self.p.state, 'start failed')
with patch('subprocess.call', return_value=0): with patch('subprocess.call', return_value=0):
self.p._state = 'running' self.p._state = 'running'
self.assertFalse(self.p.check_for_startup()) self.assertFalse(self.p.check_for_startup())
self.assertEquals(self.p.state, 'running') self.assertEqual(self.p.state, 'running')
with patch('subprocess.call', return_value=127): with patch('subprocess.call', return_value=127):
self.p._state = 'running' self.p._state = 'running'
self.assertFalse(self.p.check_for_startup()) self.assertFalse(self.p.check_for_startup())
self.assertEquals(self.p.state, 'running') self.assertEqual(self.p.state, 'running')
self.p._state = 'starting' self.p._state = 'starting'
self.assertFalse(self.p.check_for_startup()) self.assertFalse(self.p.check_for_startup())
self.assertEquals(self.p.state, 'running') self.assertEqual(self.p.state, 'running')
def test_wait_for_startup(self): def test_wait_for_startup(self):
state = {'sleeps': 0, 'num_rejects': 0, 'final_return': 0} state = {'sleeps': 0, 'num_rejects': 0, 'final_return': 0}
self.__thread_ident = current_thread().ident
def increment_sleeps(*args): def increment_sleeps(*args):
print("Sleep") if current_thread().ident == self.__thread_ident:
state['sleeps'] += 1 print("Sleep")
state['sleeps'] += 1
def isready_return(*args): def isready_return(*args):
ret = 1 if state['sleeps'] < state['num_rejects'] else state['final_return'] ret = 1 if state['sleeps'] < state['num_rejects'] else state['final_return']
@@ -784,12 +506,12 @@ class TestPostgresql(unittest.TestCase):
self.p._state = 'stopped' self.p._state = 'stopped'
self.assertTrue(self.p.wait_for_startup()) self.assertTrue(self.p.wait_for_startup())
self.assertEquals(state['sleeps'], 0) self.assertEqual(state['sleeps'], 0)
self.p._state = 'starting' self.p._state = 'starting'
state['num_rejects'] = 5 state['num_rejects'] = 5
self.assertTrue(self.p.wait_for_startup()) self.assertTrue(self.p.wait_for_startup())
self.assertEquals(state['sleeps'], 5) self.assertEqual(state['sleeps'], 5)
self.p._state = 'starting' self.p._state = 'starting'
state['sleeps'] = 0 state['sleeps'] = 0
@@ -800,23 +522,13 @@ class TestPostgresql(unittest.TestCase):
state['sleeps'] = 0 state['sleeps'] = 0
state['final_return'] = 0 state['final_return'] = 0
self.assertFalse(self.p.wait_for_startup(timeout=2)) self.assertFalse(self.p.wait_for_startup(timeout=2))
self.assertEquals(state['sleeps'], 3) self.assertEqual(state['sleeps'], 3)
with patch.object(Postgresql, 'check_startup_state_changed', Mock(return_value=False)): with patch.object(Postgresql, 'check_startup_state_changed', Mock(return_value=False)):
self.p.cancel() self.p.cancellable.cancel()
self.p._state = 'starting' self.p._state = 'starting'
self.assertIsNone(self.p.wait_for_startup()) self.assertIsNone(self.p.wait_for_startup())
def test_read_pid_file(self):
pidfile = os.path.join(self.data_dir, 'postmaster.pid')
if os.path.exists(pidfile):
os.remove(pidfile)
self.assertEquals(self.p._read_pid_file(), {})
with open(pidfile, 'w') as fd:
fd.write("123\n/foo/bar\n123456789\n5432")
self.assertEquals(self.p._read_pid_file(), {"pid": "123", "data_dir": "/foo/bar",
"start_time": "123456789", "port": "5432"})
def test_pick_sync_standby(self): def test_pick_sync_standby(self):
cluster = Cluster(True, None, self.leader, 0, [self.me, self.other, self.leadermem], None, cluster = Cluster(True, None, self.leader, 0, [self.me, self.other, self.leadermem], None,
SyncState(0, self.me.name, self.leadermem.name), None) SyncState(0, self.me.name, self.leadermem.name), None)
@@ -826,64 +538,64 @@ class TestPostgresql(unittest.TestCase):
(self.me.name, 'streaming', 'async'), (self.me.name, 'streaming', 'async'),
(self.other.name, 'streaming', 'async'), (self.other.name, 'streaming', 'async'),
]): ]):
self.assertEquals(self.p.pick_synchronous_standby(cluster), (self.leadermem.name, True)) self.assertEqual(self.p.pick_synchronous_standby(cluster), (self.leadermem.name, True))
with patch.object(Postgresql, "query", return_value=[ with patch.object(Postgresql, "query", return_value=[
(self.me.name, 'streaming', 'async'), (self.me.name, 'streaming', 'async'),
(self.leadermem.name, 'streaming', 'potential'), (self.leadermem.name, 'streaming', 'potential'),
(self.other.name, 'streaming', 'async'), (self.other.name, 'streaming', 'async'),
]): ]):
self.assertEquals(self.p.pick_synchronous_standby(cluster), (self.leadermem.name, False)) self.assertEqual(self.p.pick_synchronous_standby(cluster), (self.leadermem.name, False))
with patch.object(Postgresql, "query", return_value=[ with patch.object(Postgresql, "query", return_value=[
(self.me.name, 'streaming', 'async'), (self.me.name, 'streaming', 'async'),
(self.other.name, 'streaming', 'async'), (self.other.name, 'streaming', 'async'),
]): ]):
self.assertEquals(self.p.pick_synchronous_standby(cluster), (self.me.name, False)) self.assertEqual(self.p.pick_synchronous_standby(cluster), (self.me.name, False))
with patch.object(Postgresql, "query", return_value=[ with patch.object(Postgresql, "query", return_value=[
('missing', 'streaming', 'sync'), ('missing', 'streaming', 'sync'),
(self.me.name, 'streaming', 'async'), (self.me.name, 'streaming', 'async'),
(self.other.name, 'streaming', 'async'), (self.other.name, 'streaming', 'async'),
]): ]):
self.assertEquals(self.p.pick_synchronous_standby(cluster), (self.me.name, False)) self.assertEqual(self.p.pick_synchronous_standby(cluster), (self.me.name, False))
with patch.object(Postgresql, "query", return_value=[]): with patch.object(Postgresql, "query", return_value=[]):
self.assertEquals(self.p.pick_synchronous_standby(cluster), (None, False)) self.assertEqual(self.p.pick_synchronous_standby(cluster), (None, False))
def test_set_sync_standby(self): def test_set_sync_standby(self):
def value_in_conf(): def value_in_conf():
with open(os.path.join(self.data_dir, 'postgresql.conf')) as f: with open(os.path.join(self.p.data_dir, 'postgresql.conf')) as f:
for line in f: for line in f:
if line.startswith('synchronous_standby_names'): if line.startswith('synchronous_standby_names'):
return line.strip() return line.strip()
mock_reload = self.p.reload = Mock() mock_reload = self.p.reload = Mock()
self.p.set_synchronous_standby('n1') self.p.config.set_synchronous_standby('n1')
self.assertEquals(value_in_conf(), "synchronous_standby_names = 'n1'") self.assertEqual(value_in_conf(), "synchronous_standby_names = 'n1'")
mock_reload.assert_called() mock_reload.assert_called()
mock_reload.reset_mock() mock_reload.reset_mock()
self.p.set_synchronous_standby('n1') self.p.config.set_synchronous_standby('n1')
mock_reload.assert_not_called() mock_reload.assert_not_called()
self.assertEquals(value_in_conf(), "synchronous_standby_names = 'n1'") self.assertEqual(value_in_conf(), "synchronous_standby_names = 'n1'")
self.p.set_synchronous_standby('n2') self.p.config.set_synchronous_standby('n2')
mock_reload.assert_called() mock_reload.assert_called()
self.assertEquals(value_in_conf(), "synchronous_standby_names = 'n2'") self.assertEqual(value_in_conf(), "synchronous_standby_names = 'n2'")
mock_reload.reset_mock() mock_reload.reset_mock()
self.p.set_synchronous_standby(None) self.p.config.set_synchronous_standby(None)
mock_reload.assert_called() mock_reload.assert_called()
self.assertEquals(value_in_conf(), None) self.assertEqual(value_in_conf(), None)
def test_get_server_parameters(self): def test_get_server_parameters(self):
config = {'synchronous_mode': True, 'parameters': {'wal_level': 'hot_standby'}, 'listen': '0'} config = {'synchronous_mode': True, 'parameters': {'wal_level': 'hot_standby'}, 'listen': '0'}
self.p.get_server_parameters(config) self.p.config.get_server_parameters(config)
config['synchronous_mode_strict'] = True config['synchronous_mode_strict'] = True
self.p.get_server_parameters(config) self.p.config.get_server_parameters(config)
self.p.set_synchronous_standby('foo') self.p.config.set_synchronous_standby('foo')
self.p.get_server_parameters(config) self.p.config.get_server_parameters(config)
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
def test__wait_for_connection_close(self): def test__wait_for_connection_close(self):
@@ -909,8 +621,8 @@ class TestPostgresql(unittest.TestCase):
"--wal_log_hints=on" "--max_wal_senders=5" "--max_replication_slots=5"\n') "--wal_log_hints=on" "--max_wal_senders=5" "--max_replication_slots=5"\n')
with patch.object(builtins, 'open', m): with patch.object(builtins, 'open', m):
data = self.p.read_postmaster_opts() data = self.p.read_postmaster_opts()
self.assertEquals(data['wal_level'], 'hot_standby') self.assertEqual(data['wal_level'], 'hot_standby')
self.assertEquals(int(data['max_replication_slots']), 5) self.assertEqual(int(data['max_replication_slots']), 5)
self.assertEqual(data.get('D'), None) self.assertEqual(data.get('D'), None)
m.side_effect = IOError m.side_effect = IOError
@@ -920,7 +632,7 @@ class TestPostgresql(unittest.TestCase):
@patch('subprocess.Popen') @patch('subprocess.Popen')
def test_single_user_mode(self, subprocess_popen_mock): def test_single_user_mode(self, subprocess_popen_mock):
subprocess_popen_mock.return_value.wait.return_value = 0 subprocess_popen_mock.return_value.wait.return_value = 0
self.assertEquals(self.p.single_user_mode('CHECKPOINT', {'archive_mode': 'on'}), 0) self.assertEqual(self.p.single_user_mode('CHECKPOINT', {'archive_mode': 'on'}), 0)
@patch('os.listdir', Mock(side_effect=[OSError, ['a', 'b']])) @patch('os.listdir', Mock(side_effect=[OSError, ['a', 'b']]))
@patch('os.unlink', Mock(side_effect=OSError)) @patch('os.unlink', Mock(side_effect=OSError))
@@ -932,25 +644,27 @@ class TestPostgresql(unittest.TestCase):
self.p.cleanup_archive_status() self.p.cleanup_archive_status()
@patch('os.unlink', Mock()) @patch('os.unlink', Mock())
@patch('os.listdir', Mock(return_value=[]))
@patch('os.path.isfile', Mock(return_value=True)) @patch('os.path.isfile', Mock(return_value=True))
@patch.object(Postgresql, 'read_postmaster_opts', Mock(return_value={}))
@patch.object(Postgresql, 'single_user_mode', Mock(return_value=0)) @patch.object(Postgresql, 'single_user_mode', Mock(return_value=0))
def test_fix_cluster_state(self): def test_fix_cluster_state(self):
self.assertTrue(self.p.fix_cluster_state()) self.assertTrue(self.p.fix_cluster_state())
def test_replica_cached_timeline(self): def test_replica_cached_timeline(self):
self.assertEquals(self.p.replica_cached_timeline(1), 2) self.assertEqual(self.p.replica_cached_timeline(1), 2)
def test_get_master_timeline(self): def test_get_master_timeline(self):
self.assertEquals(self.p.get_master_timeline(), 1) self.assertEqual(self.p.get_master_timeline(), 1)
def test_cancellable_subprocess_call(self): @patch.object(Postgresql, 'get_postgres_role_from_data_directory', Mock(return_value='replica'))
self.p.cancel() def test__build_effective_configuration(self):
self.assertRaises(PostgresException, self.p.cancellable_subprocess_call) with patch.object(Postgresql, 'controldata',
Mock(return_value={'max_connections setting': '200',
@patch('patroni.postgresql.polling_loop', Mock(return_value=[0, 0])) 'max_worker_processes setting': '20',
def test_cancel(self): 'max_prepared_xacts setting': '100',
self.p._cancellable = Mock() 'max_locks_per_xact setting': '100',
self.p._cancellable.returncode = None 'max_wal_senders setting': 10})):
self.p.cancel() self.p.cancellable.cancel()
type(self.p._cancellable).returncode = PropertyMock(side_effect=[None, -15]) self.assertFalse(self.p.start())
self.p.cancel() self.assertTrue(self.p.pending_restart)
+61 -27
View File
@@ -1,8 +1,21 @@
import psutil
import unittest import unittest
from mock import Mock, patch from mock import Mock, patch, mock_open
from patroni.postmaster import PostmasterProcess from patroni.postgresql.postmaster import PostmasterProcess
import psutil from six.moves import builtins
class MockProcess(object):
def __init__(self, target, args):
self.target = target
self.args = args
def start(self):
self.target(*self.args)
def join(self):
pass
class TestPostmasterProcess(unittest.TestCase): class TestPostmasterProcess(unittest.TestCase):
@@ -13,52 +26,60 @@ class TestPostmasterProcess(unittest.TestCase):
@patch('psutil.Process.create_time') @patch('psutil.Process.create_time')
@patch('psutil.Process.__init__') @patch('psutil.Process.__init__')
def test_from_pidfile(self, mock_init, mock_create_time): @patch.object(PostmasterProcess, '_read_postmaster_pidfile')
def test_from_pidfile(self, mock_read, mock_init, mock_create_time):
mock_init.side_effect = psutil.NoSuchProcess(123) mock_init.side_effect = psutil.NoSuchProcess(123)
self.assertEquals(PostmasterProcess.from_pidfile({}), None) mock_read.return_value = {}
self.assertEquals(PostmasterProcess.from_pidfile({"pid": "foo"}), None) self.assertIsNone(PostmasterProcess.from_pidfile(''))
self.assertEquals(PostmasterProcess.from_pidfile({"pid": "123"}), None) mock_read.return_value = {"pid": "foo"}
self.assertIsNone(PostmasterProcess.from_pidfile(''))
mock_read.return_value = {"pid": "123"}
self.assertIsNone(PostmasterProcess.from_pidfile(''))
mock_init.side_effect = None mock_init.side_effect = None
with patch.object(psutil.Process, 'pid', 123), \ with patch.object(psutil.Process, 'pid', 123), \
patch.object(psutil.Process, 'parent', return_value=124), \ patch.object(psutil.Process, 'ppid', return_value=124), \
patch('os.getpid', return_value=125) as mock_ospid, \ patch('os.getpid', return_value=125) as mock_ospid, \
patch('os.getppid', return_value=126): patch('os.getppid', return_value=126):
self.assertNotEquals(PostmasterProcess.from_pidfile({"pid": "123"}), None) self.assertIsNotNone(PostmasterProcess.from_pidfile(''))
mock_create_time.return_value = 100000 mock_create_time.return_value = 100000
self.assertEquals(PostmasterProcess.from_pidfile({"pid": "123", "start_time": "200000"}), None) mock_read.return_value = {"pid": "123", "start_time": "200000"}
self.assertNotEquals(PostmasterProcess.from_pidfile({"pid": "123", "start_time": "foobar"}), None) self.assertIsNone(PostmasterProcess.from_pidfile(''))
mock_read.return_value = {"pid": "123", "start_time": "foobar"}
self.assertIsNotNone(PostmasterProcess.from_pidfile(''))
mock_ospid.return_value = 123 mock_ospid.return_value = 123
self.assertEquals(PostmasterProcess.from_pidfile({"pid": "123", "start_time": "100000"}), None) mock_read.return_value = {"pid": "123", "start_time": "100000"}
self.assertIsNone(PostmasterProcess.from_pidfile(''))
@patch('psutil.Process.__init__') @patch('psutil.Process.__init__')
def test_from_pid(self, mock_init): def test_from_pid(self, mock_init):
mock_init.side_effect = psutil.NoSuchProcess(123) mock_init.side_effect = psutil.NoSuchProcess(123)
self.assertEquals(PostmasterProcess.from_pid(123), None) self.assertEqual(PostmasterProcess.from_pid(123), None)
mock_init.side_effect = None mock_init.side_effect = None
self.assertNotEquals(PostmasterProcess.from_pid(123), None) self.assertNotEqual(PostmasterProcess.from_pid(123), None)
@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))
def test_signal_stop(self, mock_send_signal): def test_signal_stop(self, mock_send_signal):
proc = PostmasterProcess(-123) proc = PostmasterProcess(-123)
self.assertEquals(proc.signal_stop('immediate'), False) self.assertEqual(proc.signal_stop('immediate'), False)
mock_send_signal.side_effect = [None, psutil.NoSuchProcess(123), psutil.AccessDenied()] mock_send_signal.side_effect = [None, psutil.NoSuchProcess(123), psutil.AccessDenied()]
proc = PostmasterProcess(123) proc = PostmasterProcess(123)
self.assertEquals(proc.signal_stop('immediate'), None) self.assertEqual(proc.signal_stop('immediate'), None)
self.assertEquals(proc.signal_stop('immediate'), True) self.assertEqual(proc.signal_stop('immediate'), True)
self.assertEquals(proc.signal_stop('immediate'), False) self.assertEqual(proc.signal_stop('immediate'), False)
@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):
c1 = Mock() c1 = Mock()
c1.cmdline = Mock(return_value=["postgres: startup process"]) c1.cmdline = Mock(return_value=["postgres: startup process "])
c2 = Mock() c2 = Mock()
c2.cmdline = Mock(return_value=["postgres: postgres postgres [local] idle"]) c2.cmdline = Mock(return_value=["postgres: postgres postgres [local] idle"])
c3 = Mock() c3 = Mock()
@@ -68,18 +89,31 @@ class TestPostmasterProcess(unittest.TestCase):
self.assertIsNone(proc.wait_for_user_backends_to_close()) self.assertIsNone(proc.wait_for_user_backends_to_close())
mock_wait.assert_called_with([c2]) mock_wait.assert_called_with([c2])
c3.cmdline = Mock(side_effect=psutil.AccessDenied(123)) with patch('psutil.Process.children', Mock(side_effect=psutil.NoSuchProcess(123))):
with patch('psutil.Process.children', Mock(return_value=[c3])):
proc = PostmasterProcess(123) proc = PostmasterProcess(123)
self.assertIsNone(proc.wait_for_user_backends_to_close()) self.assertIsNone(proc.wait_for_user_backends_to_close())
@patch('subprocess.Popen') @patch('subprocess.Popen')
@patch('os.setsid', Mock(), create=True)
@patch('multiprocessing.Process', MockProcess)
@patch.object(PostmasterProcess, 'from_pid') @patch.object(PostmasterProcess, 'from_pid')
def test_start(self, mock_frompid, mock_popen): @patch.object(PostmasterProcess, '_from_pidfile')
def test_start(self, mock_frompidfile, mock_frompid, mock_popen):
mock_frompidfile.return_value._is_postmaster_process.return_value = False
mock_frompid.return_value = "proc 123" mock_frompid.return_value = "proc 123"
mock_popen.return_value.stdout.readline.return_value = '123' mock_popen.return_value.pid = 123
self.assertEquals( self.assertEqual(PostmasterProcess.start('true', '/tmp', '/tmp/test.conf', []), "proc 123")
PostmasterProcess.start('/bin/true', '/tmp/', '/tmp/test.conf', ['--foo=bar', '--bar=baz']),
"proc 123"
)
mock_frompid.assert_called_with(123) mock_frompid.assert_called_with(123)
mock_frompidfile.side_effect = psutil.NoSuchProcess(123)
self.assertEqual(PostmasterProcess.start('true', '/tmp', '/tmp/test.conf', []), "proc 123")
mock_popen.side_effect = Exception
self.assertIsNone(PostmasterProcess.start('true', '/tmp', '/tmp/test.conf', []))
@patch('psutil.Process.__init__', Mock(side_effect=psutil.NoSuchProcess(123)))
def test_read_postmaster_pidfile(self):
with patch.object(builtins, 'open', Mock(side_effect=IOError)):
self.assertIsNone(PostmasterProcess.from_pidfile(''))
with patch.object(builtins, 'open', mock_open(read_data='123\n')):
self.assertIsNone(PostmasterProcess.from_pidfile(''))
+107
View File
@@ -0,0 +1,107 @@
from mock import Mock, PropertyMock, patch
from patroni.postgresql import Postgresql
from patroni.postgresql.cancellable import CancellableSubprocess
from patroni.postgresql.rewind import Rewind
from . import BaseTestPostgresql, MockCursor, psycopg2_connect
@patch('subprocess.call', Mock(return_value=0))
@patch('psycopg2.connect', psycopg2_connect)
class TestRewind(BaseTestPostgresql):
def setUp(self):
super(TestRewind, self).setUp()
self.r = Rewind(self.p)
def test_can_rewind(self):
with patch.object(Postgresql, 'controldata', Mock(return_value={'wal_log_hints setting': 'on'})):
self.assertTrue(self.r.can_rewind)
with patch('subprocess.call', Mock(return_value=1)):
self.assertFalse(self.r.can_rewind)
with patch('subprocess.call', side_effect=OSError):
self.assertFalse(self.r.can_rewind)
self.p.config._config['use_pg_rewind'] = False
self.assertFalse(self.r.can_rewind)
@patch.object(CancellableSubprocess, 'call')
def test_pg_rewind(self, mock_cancellable_subprocess_call):
r = {'user': '', 'host': '', 'port': '', 'database': '', 'password': ''}
mock_cancellable_subprocess_call.return_value = 0
self.assertTrue(self.r.pg_rewind(r))
mock_cancellable_subprocess_call.side_effect = OSError
self.assertFalse(self.r.pg_rewind(r))
@patch.object(Rewind, 'can_rewind', PropertyMock(return_value=True))
def test__get_local_timeline_lsn(self):
self.r.trigger_check_diverged_lsn()
with patch.object(Postgresql, 'controldata',
Mock(return_value={'Database cluster state': 'shut down in recovery',
'Minimum recovery ending location': '0/0',
"Min recovery ending loc's timeline": '0'})):
self.r.rewind_or_reinitialize_needed_and_possible(self.leader)
with patch.object(Postgresql, 'is_running', Mock(return_value=True)):
with patch.object(MockCursor, 'fetchone', Mock(side_effect=[(False, ), Exception])):
self.r.rewind_or_reinitialize_needed_and_possible(self.leader)
@patch.object(CancellableSubprocess, 'call', Mock(return_value=0))
@patch.object(Postgresql, 'checkpoint', side_effect=['', '1'],)
@patch.object(Postgresql, 'stop', Mock(return_value=False))
@patch.object(Postgresql, 'start', Mock())
def test_execute(self, mock_checkpoint):
self.r.execute(self.leader)
with patch.object(Rewind, 'pg_rewind', Mock(return_value=False)):
mock_checkpoint.side_effect = ['1', '', '', '']
self.r.execute(self.leader)
self.r.execute(self.leader)
with patch.object(Rewind, 'check_leader_is_not_in_recovery', Mock(return_value=False)):
self.r.execute(self.leader)
self.p.config._config['remove_data_directory_on_rewind_failure'] = False
self.r.trigger_check_diverged_lsn()
self.r.execute(self.leader)
self.leader.member.data.update(version='1.5.7', checkpoint_after_promote=False, role='master')
self.assertIsNone(self.r.execute(self.leader))
del self.leader.member.data['checkpoint_after_promote']
with patch.object(Rewind, 'check_leader_is_not_in_recovery', Mock(return_value=False)):
self.assertIsNone(self.r.execute(self.leader))
with patch.object(Postgresql, 'is_running', Mock(return_value=True)):
self.r.execute(self.leader)
@patch.object(Postgresql, 'start', Mock())
@patch.object(Rewind, 'can_rewind', PropertyMock(return_value=True))
@patch.object(Rewind, '_get_local_timeline_lsn', Mock(return_value=(2, '40159C1')))
@patch.object(Rewind, 'check_leader_is_not_in_recovery')
def test__check_timeline_and_lsn(self, mock_check_leader_is_not_in_recovery):
mock_check_leader_is_not_in_recovery.return_value = False
self.r.trigger_check_diverged_lsn()
self.assertFalse(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
self.leader = self.leader.member
self.assertFalse(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
mock_check_leader_is_not_in_recovery.return_value = True
self.assertFalse(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
self.r.trigger_check_diverged_lsn()
with patch('psycopg2.connect', Mock(side_effect=Exception)):
self.assertFalse(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
self.r.trigger_check_diverged_lsn()
with patch.object(MockCursor, 'fetchone', Mock(side_effect=[('', 2, '0/0'), ('', b'3\t0/40159C0\tn\n')])):
self.assertFalse(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
self.r.trigger_check_diverged_lsn()
with patch.object(MockCursor, 'fetchone', Mock(return_value=('', 1, '0/0'))):
with patch.object(Rewind, '_get_local_timeline_lsn', Mock(return_value=(1, '0/0'))):
self.assertFalse(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
self.r.trigger_check_diverged_lsn()
self.assertTrue(self.r.rewind_or_reinitialize_needed_and_possible(self.leader))
@patch.object(MockCursor, 'fetchone', Mock(side_effect=[(True,), Exception]))
def test_check_leader_is_not_in_recovery(self):
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}))
def test_check_for_checkpoint_after_promote(self):
self.r.check_for_checkpoint_after_promote()
+5 -5
View File
@@ -8,7 +8,7 @@ from patroni.utils import Retry, RetryFailedError, polling_loop
class TestUtils(unittest.TestCase): class TestUtils(unittest.TestCase):
def test_polling_loop(self): def test_polling_loop(self):
self.assertEquals(list(polling_loop(0.001, interval=0.001)), [0]) self.assertEqual(list(polling_loop(0.001, interval=0.001)), [0])
@patch('time.sleep', Mock()) @patch('time.sleep', Mock())
@@ -29,21 +29,21 @@ class TestRetrySleeper(unittest.TestCase):
def test_reset(self): def test_reset(self):
retry = Retry(delay=0, max_tries=2) retry = Retry(delay=0, max_tries=2)
retry(self._fail()) retry(self._fail())
self.assertEquals(retry._attempts, 1) self.assertEqual(retry._attempts, 1)
retry.reset() retry.reset()
self.assertEquals(retry._attempts, 0) self.assertEqual(retry._attempts, 0)
def test_too_many_tries(self): def test_too_many_tries(self):
retry = Retry(delay=0) retry = Retry(delay=0)
self.assertRaises(RetryFailedError, retry, self._fail(times=999)) self.assertRaises(RetryFailedError, retry, self._fail(times=999))
self.assertEquals(retry._attempts, 1) self.assertEqual(retry._attempts, 1)
def test_maximum_delay(self): def test_maximum_delay(self):
retry = Retry(delay=10, max_tries=100) retry = Retry(delay=10, max_tries=100)
retry(self._fail(times=10)) retry(self._fail(times=10))
self.assertTrue(retry._cur_delay < 4000, retry._cur_delay) self.assertTrue(retry._cur_delay < 4000, retry._cur_delay)
# gevent's sleep function is picky about the type # gevent's sleep function is picky about the type
self.assertEquals(type(retry._cur_delay), float) self.assertEqual(type(retry._cur_delay), float)
def test_deadline(self): def test_deadline(self):
retry = Retry(deadline=0.0001) retry = Retry(deadline=0.0001)
+21 -8
View File
@@ -6,8 +6,9 @@ from mock import Mock, PropertyMock, patch, mock_open
from patroni.scripts import wale_restore from patroni.scripts import wale_restore
from patroni.scripts.wale_restore import WALERestore, main as _main, get_major_version from patroni.scripts.wale_restore import WALERestore, main as _main, get_major_version
from six.moves import builtins from six.moves import builtins
from test_postgresql import MockConnect, psycopg2_connect from threading import current_thread
from . import MockConnect, psycopg2_connect
wale_output_header = ( wale_output_header = (
b'name\tlast_modified\t' b'name\tlast_modified\t'
@@ -42,6 +43,13 @@ class TestWALERestore(unittest.TestCase):
'/etc', 100, 100, 1, 0, WALE_TEST_RETRIES) '/etc', 100, 100, 1, 0, WALE_TEST_RETRIES)
def test_should_use_s3_to_create_replica(self): def test_should_use_s3_to_create_replica(self):
self.__thread_ident = current_thread().ident
sleeps = [0]
def mock_sleep(*args):
if current_thread().ident == self.__thread_ident:
sleeps[0] += 1
self.assertTrue(self.wale_restore.should_use_s3_to_create_replica()) self.assertTrue(self.wale_restore.should_use_s3_to_create_replica())
with patch.object(MockConnect, 'server_version', PropertyMock(return_value=100000)): with patch.object(MockConnect, 'server_version', PropertyMock(return_value=100000)):
self.assertTrue(self.wale_restore.should_use_s3_to_create_replica()) self.assertTrue(self.wale_restore.should_use_s3_to_create_replica())
@@ -55,13 +63,11 @@ class TestWALERestore(unittest.TestCase):
self.assertFalse(self.wale_restore.should_use_s3_to_create_replica()) self.assertFalse(self.wale_restore.should_use_s3_to_create_replica())
with patch('time.sleep', Mock(return_value=None)) as mock_sleep: with patch('time.sleep', mock_sleep):
self.wale_restore.no_master = 1 self.wale_restore.no_master = 1
assert self.wale_restore.should_use_s3_to_create_replica() self.assertTrue(self.wale_restore.should_use_s3_to_create_replica())
# verify retries # verify retries
mock_sleep.assert_has_calls( self.assertEqual(sleeps[0], WALE_TEST_RETRIES)
[((wale_restore.RETRY_SLEEP_INTERVAL,),)] * WALE_TEST_RETRIES
)
self.wale_restore.master_connection = '' self.wale_restore.master_connection = ''
self.assertTrue(self.wale_restore.should_use_s3_to_create_replica()) self.assertTrue(self.wale_restore.should_use_s3_to_create_replica())
@@ -104,13 +110,20 @@ class TestWALERestore(unittest.TestCase):
@patch('sys.exit', Mock()) @patch('sys.exit', Mock())
def test_main(self): def test_main(self):
self.__thread_ident = current_thread().ident
sleeps = [0]
def mock_sleep(*args):
if current_thread().ident == self.__thread_ident:
sleeps[0] += 1
with patch.object(WALERestore, 'run', Mock(return_value=0)): with patch.object(WALERestore, 'run', Mock(return_value=0)):
self.assertEqual(_main(), 0) self.assertEqual(_main(), 0)
with patch.object(WALERestore, 'run', Mock(return_value=1)), \ with patch.object(WALERestore, 'run', Mock(return_value=1)), \
patch('time.sleep', Mock(return_value=None)) as mock_sleep: patch('time.sleep', mock_sleep):
self.assertEqual(_main(), 1) self.assertEqual(_main(), 1)
assert mock_sleep.call_count == WALE_TEST_RETRIES self.assertTrue(sleeps[0], WALE_TEST_RETRIES)
@patch('os.path.isfile', Mock(return_value=True)) @patch('os.path.isfile', Mock(return_value=True))
def test_get_major_version(self): def test_get_major_version(self):
+14 -11
View File
@@ -2,6 +2,7 @@ import ctypes
import patroni.watchdog.linux as linuxwd import patroni.watchdog.linux as linuxwd
import sys import sys
import unittest import unittest
import os
from mock import patch, Mock, PropertyMock from mock import patch, Mock, PropertyMock
from patroni.watchdog import Watchdog, WatchdogError from patroni.watchdog import Watchdog, WatchdogError
@@ -61,6 +62,7 @@ def mock_close(fd):
mock_devices[fd].open = False mock_devices[fd].open = False
@unittest.skipIf(os.name == 'nt', "Windows not supported")
@patch('os.open', mock_open) @patch('os.open', mock_open)
@patch('os.write', mock_write) @patch('os.write', mock_write)
@patch('os.close', mock_close) @patch('os.close', mock_close)
@@ -73,14 +75,14 @@ class TestWatchdog(unittest.TestCase):
@patch.object(LinuxWatchdogDevice, 'can_be_disabled', PropertyMock(return_value=True)) @patch.object(LinuxWatchdogDevice, 'can_be_disabled', PropertyMock(return_value=True))
def test_unsafe_timeout_disable_watchdog_and_exit(self): def test_unsafe_timeout_disable_watchdog_and_exit(self):
watchdog = Watchdog({'ttl': 30, 'loop_wait': 15, 'watchdog': {'mode': 'required', 'safety_margin': -1}}) watchdog = Watchdog({'ttl': 30, 'loop_wait': 15, 'watchdog': {'mode': 'required', 'safety_margin': -1}})
self.assertEquals(watchdog.activate(), False) self.assertEqual(watchdog.activate(), False)
self.assertEquals(watchdog.is_running, False) self.assertEqual(watchdog.is_running, False)
@patch('platform.system', Mock(return_value='Linux')) @patch('platform.system', Mock(return_value='Linux'))
@patch.object(LinuxWatchdogDevice, 'get_timeout', Mock(return_value=16)) @patch.object(LinuxWatchdogDevice, 'get_timeout', Mock(return_value=16))
def test_timeout_does_not_ensure_safe_termination(self): def test_timeout_does_not_ensure_safe_termination(self):
Watchdog({'ttl': 30, 'loop_wait': 15, 'watchdog': {'mode': 'auto', 'safety_margin': -1}}).activate() Watchdog({'ttl': 30, 'loop_wait': 15, 'watchdog': {'mode': 'auto', 'safety_margin': -1}}).activate()
self.assertEquals(len(mock_devices), 2) self.assertEqual(len(mock_devices), 2)
@patch('platform.system', Mock(return_value='Linux')) @patch('platform.system', Mock(return_value='Linux'))
@patch.object(Watchdog, 'is_running', PropertyMock(return_value=False)) @patch.object(Watchdog, 'is_running', PropertyMock(return_value=False))
@@ -99,29 +101,29 @@ class TestWatchdog(unittest.TestCase):
watchdog = Watchdog({'ttl': 30, 'loop_wait': 10, 'watchdog': {'mode': 'required'}}) watchdog = Watchdog({'ttl': 30, 'loop_wait': 10, 'watchdog': {'mode': 'required'}})
watchdog.activate() watchdog.activate()
self.assertEquals(len(mock_devices), 2) self.assertEqual(len(mock_devices), 2)
device = mock_devices[-1] device = mock_devices[-1]
self.assertTrue(device.open) self.assertTrue(device.open)
self.assertEquals(device.timeout, 24) self.assertEqual(device.timeout, 24)
watchdog.keepalive() watchdog.keepalive()
self.assertEquals(len(device.writes), 1) self.assertEqual(len(device.writes), 1)
watchdog.disable() watchdog.disable()
self.assertFalse(device.open) self.assertFalse(device.open)
self.assertEquals(device.writes[-1], b'V') self.assertEqual(device.writes[-1], b'V')
def test_invalid_timings(self): def test_invalid_timings(self):
watchdog = Watchdog({'ttl': 30, 'loop_wait': 20, 'watchdog': {'mode': 'automatic', 'safety_margin': -1}}) watchdog = Watchdog({'ttl': 30, 'loop_wait': 20, 'watchdog': {'mode': 'automatic', 'safety_margin': -1}})
watchdog.activate() watchdog.activate()
self.assertEquals(len(mock_devices), 1) self.assertEqual(len(mock_devices), 1)
self.assertFalse(watchdog.is_running) self.assertFalse(watchdog.is_running)
def test_parse_mode(self): def test_parse_mode(self):
with patch('patroni.watchdog.base.logger.warning', new_callable=Mock()) as warning_mock: with patch('patroni.watchdog.base.logger.warning', new_callable=Mock()) as warning_mock:
watchdog = Watchdog({'ttl': 30, 'loop_wait': 10, 'watchdog': {'mode': 'bad'}}) watchdog = Watchdog({'ttl': 30, 'loop_wait': 10, 'watchdog': {'mode': 'bad'}})
self.assertEquals(watchdog.config.mode, 'off') self.assertEqual(watchdog.config.mode, 'off')
warning_mock.assert_called_once() warning_mock.assert_called_once()
@patch('platform.system', Mock(return_value='Unknown')) @patch('platform.system', Mock(return_value='Unknown'))
@@ -170,10 +172,11 @@ class TestNullWatchdog(unittest.TestCase):
watchdog = NullWatchdog() watchdog = NullWatchdog()
self.assertTrue(watchdog.can_be_disabled) self.assertTrue(watchdog.can_be_disabled)
self.assertRaises(WatchdogError, watchdog.set_timeout, 1) self.assertRaises(WatchdogError, watchdog.set_timeout, 1)
self.assertEquals(watchdog.describe(), 'NullWatchdog') self.assertEqual(watchdog.describe(), 'NullWatchdog')
self.assertIsInstance(NullWatchdog.from_config({}), NullWatchdog) self.assertIsInstance(NullWatchdog.from_config({}), NullWatchdog)
@unittest.skipIf(os.name == 'nt', "Windows not supported")
class TestLinuxWatchdogDevice(unittest.TestCase): class TestLinuxWatchdogDevice(unittest.TestCase):
def setUp(self): def setUp(self):
@@ -210,7 +213,7 @@ class TestLinuxWatchdogDevice(unittest.TestCase):
self.assertRaises(WatchdogError, self.impl.get_timeout) self.assertRaises(WatchdogError, self.impl.get_timeout)
self.assertRaises(WatchdogError, self.impl.set_timeout, 10) self.assertRaises(WatchdogError, self.impl.set_timeout, 10)
# We still try to output a reasonable string even if getting info errors # We still try to output a reasonable string even if getting info errors
self.assertEquals(self.impl.describe(), "Linux watchdog device") self.assertEqual(self.impl.describe(), "Linux watchdog device")
@patch('os.open', Mock(side_effect=OSError)) @patch('os.open', Mock(side_effect=OSError))
def test_open(self): def test_open(self):
+11 -3
View File
@@ -1,3 +1,4 @@
import select
import six import six
import unittest import unittest
@@ -16,6 +17,7 @@ class MockKazooClient(Mock):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(MockKazooClient, self).__init__() super(MockKazooClient, self).__init__()
self._session_timeout = 30
@property @property
def client_id(self): def client_id(self):
@@ -23,7 +25,7 @@ class MockKazooClient(Mock):
@staticmethod @staticmethod
def retry(func, *args, **kwargs): def retry(func, *args, **kwargs):
func(*args, **kwargs) return func(*args, **kwargs)
def get(self, path, watch=None): def get(self, path, watch=None):
if not isinstance(path, six.string_types): if not isinstance(path, six.string_types):
@@ -113,6 +115,11 @@ class TestPatroniSequentialThreadingHandler(unittest.TestCase):
def test_create_connection(self): def test_create_connection(self):
self.assertIsNotNone(self.handler.create_connection(())) self.assertIsNotNone(self.handler.create_connection(()))
self.assertIsNotNone(self.handler.create_connection((), 40)) self.assertIsNotNone(self.handler.create_connection((), 40))
self.assertIsNotNone(self.handler.create_connection(timeout=40))
@patch.object(SequentialThreadingHandler, 'select', Mock(side_effect=ValueError))
def test_select(self):
self.assertRaises(select.error, self.handler.select)
class TestZooKeeper(unittest.TestCase): class TestZooKeeper(unittest.TestCase):
@@ -156,7 +163,7 @@ class TestZooKeeper(unittest.TestCase):
self.zk.set_failover_value('Exception') self.zk.set_failover_value('Exception')
def test_set_config_value(self): def test_set_config_value(self):
self.zk.set_config_value('') self.zk.set_config_value('', 1)
self.zk.set_config_value('ok') self.zk.set_config_value('ok')
self.zk.set_config_value('Exception') self.zk.set_config_value('Exception')
@@ -179,7 +186,8 @@ class TestZooKeeper(unittest.TestCase):
self.zk.touch_member({'retry': 'retry'}) self.zk.touch_member({'retry': 'retry'})
self.zk._fetch_cluster = True self.zk._fetch_cluster = True
self.zk.get_cluster() self.zk.get_cluster()
self.zk.touch_member({'retry': 'retry'}) self.zk.touch_member({'conn_url': 'postgres://repuser:rep-pass@localhost:5434/postgres',
'api_url': 'http://127.0.0.1:8009/patroni'})
def test_take_leader(self): def test_take_leader(self):
self.zk.take_leader() self.zk.take_leader()