Repository navigation
Expand file tree
/
Copy pathpostgresql.sh
More file actions
executable file
·356 lines (295 loc) · 8.51 KB
/
Copy pathpostgresql.sh
File metadata and controls
executable file
·356 lines (295 loc) · 8.51 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#!/bin/sh
#
# postgresql.sh
#
#
# Pre- and post-snapshot and post-restore execution hooks for PostgreSQL with NetApp Astra Control.
# Tested with PostgreSQL 16.4.0 deployed by Bitnami helm chart 15.5.36 and NetApp Astra Control Service 24.03.
#
# args: [pre|post]
# pre: Lock all tables and start pg_backup_start()
# post: Take database out of read-only mode
#
readonly DEBUG="${DEBUG:-"0"}"
readonly SCRIPT_NAME="${0}"
readonly VERSION="0.2"
readonly SLEEP_TIME=86400 # 1 day
readonly ebase=40
readonly esleeptime=$((ebase+1))
readonly ekill=$((ebase+2))
readonly efailedcmd=$((ebase+3))
readonly efailedcmdrc=$((ebase+4))
readonly efailedcmdres=$((ebase+5))
readonly eusage=$((ebase+6))
readonly enosleepersfound=$((ebase+7))
#
# The postgres container can use a number of variables; see
# https://hub.docker.com/_/postgres
#
# POSTGRES_PASSWORD - required
# POSTGRES_USER - optional; default: 'postgres'
# POSTGRES_DB - optional; default ${POSTGRES_USER}
# POSTGRES_HOST_AUTH_METHOD - optional; default: md5
#
readonly POSTGRES_USER="${POSTGRES_USER:-"postgres"}"
readonly POSTGRES_DB="${POSTGRES_DB:-"${POSTGRES_USER}"}"
#
# Writes the given message to standard output
#
# $* - The message to write
#
msg() {
echo "${SCRIPT_NAME}: $*"
}
#
# Writes the given message to standard output if debug logging is enabled
#
# $* - The message to write
#
debug() {
if [ "${DEBUG}" = "1" ]; then
msg "DEBUG: $*"
fi
}
#
# Writes the given information message to standard output
#
# $* - The message to write
#
info() {
msg "INFO: $*"
}
#
# Writes the given error message to standard error
#
# $* - The message to write
#
error() {
msg "ERROR: $*" 1>&2
}
#
# Prints a list of public tables that should be locked while the DB is
# frozen to standard output.
#
get_freeze_table_list() {
tables=$(PGPASSWORD="${POSTGRES_PASSWORD}" psql -v ON_ERROR_STOP=1 --tuples-only --username "${POSTGRES_USER}" --dbname "${POSTGRES_DB}" <<-EOSQL
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE';
EOSQL
)
echo "${tables}"
}
#
# Prints the list of the pids corresponding to processes executing
# a pg_sleep(${SLEEP_TIME}) in the DB.
#
get_sleeping_pids() {
sleeping_pids=$(PGPASSWORD="${POSTGRES_PASSWORD}" psql -v ON_ERROR_STOP=1 --tuples-only --username "${POSTGRES_USER}" --dbname "${POSTGRES_DB}" <<-EOSQL
SELECT pid
FROM pg_stat_activity
WHERE query~*'(${SLEEP_TIME})'
AND wait_event='PgSleep';
EOSQL
)
echo "${sleeping_pids}"
}
#
# waits for there to be a process blocking in a pg_sleep(${SLEEP_TIME}).
# Returns esleeptime if after a minute no such process is found; otherwise returns
# 0 on success.
#
wait_for_sleeper() {
timeout=60
sleeping_pids=$(get_sleeping_pids)
while [ "${sleeping_pids}" != "" ]; do
debug "... waiting for sleeper; timeout: ${timeout}"
sleep 1
timeout=$((timeout - 1))
if [ "${timeout}" = "0" ]; then
error "timed out waiting for sleeper"
return ${esleeptime}
fi
sleeping_pids=$(get_sleeping_pids)
done
return 0
}
#
# Quiesces database ${POSTGRES_DB}
#
quiesce() {
info "Quiescing database ${POSTGRES_DB}"
tableList="$(get_freeze_table_list)"
sname="netappAstraBackup"
# (1) Start the transaction
content="BEGIN; "
# (2) lock all the tables
for table in ${tableList}; do
content="${content} LOCK TABLE ${table} IN SHARE MODE; "
done
# (3) start the pg_backup_start()
content="${content} SELECT pg_backup_start('${sname}'); "
# (4) hold the tables locked
content="${content} SELECT pg_sleep(${SLEEP_TIME}); "
# (5) Commit the transaction
content="${content} COMMIT;"
cmd_file="$(createTmpFile "${content}")"
debug "Executing SQL sequence: ${content}"
(run_cmd "${cmd_file}" "${POSTGRES_DB}" "${POSTGRES_USER}" > /dev/null 2>&1) > /dev/null 2>&1 &
if ! wait_for_sleeper; then
error "timed out waiting for sleeper"
return ${esleeptime}
fi
# By this time, psql is running and has read the file
rm "${cmd_file}"
# Ask the kernel to write anything in the page cache out to the underlying media
sync;sync;sync
debug "Starting read only mode finished successfully"
info "Quiescing finished successfully"
return 0
}
#
# kills the query associated with the given pid.
# Returns 0 on success, ekill on failure.
#
kill_sleeper() {
pid="${1}"
debug "Killing sleeping process ${pid}"
result=$(PGPASSWORD="${POSTGRES_PASSWORD}" psql -v ON_ERROR_STOP=1 --tuples-only --username "${POSTGRES_USER}" --dbname "${POSTGRES_DB}" <<-EOSQL
SELECT pg_cancel_backend(${pid});
EOSQL
)
debug "kill_sleeper: result: '${result}'"
case "${result}" in
*t*)
return 0
;;
*)
return ${ekill}
;;
esac
}
#
# Kills all queries executing pg_sleep(${SLEEP_TIME}).
#
kill_all_sleepers() {
sleeping_pids=$(get_sleeping_pids)
if [ "${sleeping_pids}" == "" ]; then
error "no sleepers found"
return ${enosleepersfound}
fi
rc=${ekill}
for pid in ${sleeping_pids}; do
rc=0
if ! kill_sleeper "${pid}"; then
# Meh, try again
sleep 1
if ! kill_sleeper "${pid}"; then
error "failed to kill sleeper ${pid}"
fi
fi
done
return ${rc} # return ekill: no pid has been found. 0: there is a pid found
}
#
# Unquiesces database ${POSTGRES_DB}
#
unquiesce() {
info "Unquiesceing database ${POSTGRES_DB}"
debug "Killing all sleeping queries"
if ! kill_all_sleepers; then
# if we don't have pid for any reason, we need quit now. Otherwise, the Thaw function will fail
info "Warning: no pid has been found, no need to do next step (run_cmd)"
return 0
fi
content="select pg_backup_stop()"
cmd_file="$(createTmpFile "${content}")"
# Take database out of read-only mode
debug "Ending read only mode"
debug "Executing SQL sequence: ${content}"
if ! run_cmd "${cmd_file}" "${POSTGRES_DB}" "${POSTGRES_USER}"; then
error "Command '${content}' failed"
rm "${cmd_file}"
return ${efailedcmd}
fi
rm "${cmd_file}"
debug "Ending read-only mode finished successfully"
info "Unquiesceing finished successfully"
return 0
}
#
# Runs the given postgres command against the given database as the given
# user.
#
# ${1} - The path to the file containing the command to run
# ${2} - The database against which the function will run the command
# ${3} - The user that can perform the command
#
run_cmd() {
cmd="${1}"
db="${2}"
user="${3}"
result=""
debug "Executing external sql script [${cmd}] for database ${db}"
debug "Command: $(cat "${cmd}")"
psql="psql -d ${db} -U ${user} --single-transaction --file ${cmd}"
debug "${psql}"
result="$(PGPASSWORD=${POSTGRES_PASSWORD} ${psql} 2>&1)"
exit_status=$?
debug "result: ${result}"
if [ "${exit_status}" != "0" ]; then
error "Command [${psql}] finished with exit code [${exit_status}] and message ${result}".
return ${efailedcmdrc}
fi
if echo "${result}" | grep -qe 'WARNING\|ERROR'; then
error "Command [${psql}] finished with exit code [${exit_status}] and message ${result}".
return ${efailedcmdres}
fi
return 0
}
#
# Creates a temp file with the given content and writes its name to standard
# output
#
# $* - The content to write to the newly-generated temp file
#
createTmpFile() {
content="${*}"
tmpfile="$(mktemp 2> /dev/null)"
if [ "${tmpfile}" = "" ]; then
error "createTmpFile: mktemp failed"
tmpfile="/tmp/netapp-postgres-quiesce"
fi
echo "${content}" > "${tmpfile}"
echo "${tmpfile}"
}
#
# Logical entry point to this script
#
# ${1} - Operation, either "pre" or "post". When "pre" is specified,
# then this script will quiesce the database. When "post" is specified,
# then this script will unquiesce the database.
#
main() {
#
# The "slave" side does not support pg_backup_start. Therefore, we do nothing.
# I have tested. Even we do nothing on the "slave" side, it depends on "master" side to sync. It works fine.
#
if [ "${POSTGRES_REPLICATION_MODE}" = "slave" ]; then
return 0
fi
case "${1}" in
"pre")
quiesce
;;
"post")
unquiesce
;;
*)
error "Usage ${SCRIPT_NAME} <pre|post>"
return ${eusage}
;;
esac
}
main "$@"