-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20-replication.sh
68 lines (60 loc) · 2 KB
/
20-replication.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/bin/bash
set -e
# usage: file_env VAR [DEFAULT]
# ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
# common settings
file_env 'MAX_CONNECTIONS' 500
file_env 'WAL_KEEP_SEGMENTS' 256
file_env 'MAX_WAL_SENDERS' 100
# master/slave settings
file_env 'REPLICATION_ROLE' 'master'
file_env 'REPLICATION_USER' 'replication'
file_env 'REPLICATION_PASSWORD' ""
file_env 'REPLICATION_NETWORK' '0.0.0.0/0'
# slave settings
file_env 'POSTGRES_MASTER_HOST' 'localhost'
file_env 'POSTGRES_MASTER_PORT' 5432
if [ $REPLICATION_ROLE = "master" ]; then
psql -U postgres -c "CREATE ROLE $REPLICATION_USER WITH REPLICATION PASSWORD '$REPLICATION_PASSWORD' LOGIN"
elif [ $REPLICATION_ROLE = "slave" ]; then
# stop postgres instance and reset PGDATA,
# confs will be copied by pg_basebackup
pg_ctl -D "$PGDATA" -m fast -w stop
# make sure standby's data directory is empty
rm -r "$PGDATA"/*
pg_basebackup \
--write-recovery-conf \
--pgdata="$PGDATA" \
--xlog-method=fetch \
--username=$REPLICATION_USER \
--host=$POSTGRES_MASTER_HOST \
--port=$POSTGRES_MASTER_PORT \
--progress \
--verbose
# slave settings, ignored on master
echo "hot_standby = on" >> "$PGDATA/postgresql.conf"
# useless postgres start to fullfil docker-entrypoint.sh stop
pg_ctl -D "$PGDATA" \
-o "-c listen_addresses=''" \
-w start
fi
echo [*] $REPLICATION_ROLE instance configured!