-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupdate_hosts_file_to_point_to_master_db
69 lines (53 loc) · 1.74 KB
/
update_hosts_file_to_point_to_master_db
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
69
#!/bin/sh
# This script checks which node is the Primary database, and sets "db.l.lan" in /etc/hosts to it.
# We need this because our Node.js Postgres driver (npm::pg)
# doesn't support adding all the nodes IPs in the connection string
# There are two targetable databases:
# 10.0.4.40:5432 same location pg_j
# 192.168.56.{30,31}:5432 an spiped that targets the remote pg_j
#
# BTW, there's only a Primary + Hot-Stanby, there're no read-only replicas.
# Also, notifies syslog if there was a connection error.
db_dn="db.l.lan"
same_location=10.0.4.40
remote_location=`/bin/cat /etc/ip_inode_b`
is_primary() {
local ip=$1
local is_standby=`/usr/local/bin/psql postgres://$ip:5432 \
--quiet \
--no-align \
--no-psqlrc \
--tuples-only \
--username postgres \
--command "SELECT pg_is_in_recovery()" 2>&1`
case "$is_standby" in
"f") /bin/echo 1 ;;
"t") /bin/echo 0 ;;
*) /bin/echo 0
/usr/bin/logger "$is_standby" ;; # logs connection errors
esac
}
update_dn_in_hosts() {
local dbip=$1
/bin/cat > /tmp/etc_hosts << EOF
`/usr/bin/grep -v $db_dn /etc/hosts`
$dbip $db_dn
EOF
/bin/mv /tmp/etc_hosts /etc/hosts
}
s_is_primary=`is_primary $same_location`
r_is_primary=`is_primary $remote_location`
if [ $s_is_primary = 1 ] && [ $r_is_primary = 1 ]; then
msg="ERROR: Split Brain. Failed to switch Primary db target"
elif [ $s_is_primary = 1 ]; then
msg="Setting the db target to the SAME location pg instance"
update_dn_in_hosts $same_location
elif [ $r_is_primary = 1 ]; then
msg="Setting the db target to the REMOTE location pg instance"
update_dn_in_hosts $remote_location
else
msg="ERROR: Did not find any Primary database"
fi
/bin/echo "$msg"
/usr/bin/logger "$msg"
# vim: set ft=sh :