-
Notifications
You must be signed in to change notification settings - Fork 56
/
backup.mongo.plugin
297 lines (253 loc) · 8.44 KB
/
backup.mongo.plugin
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
#!/bin/bash
# =================================================================================================================
# Mongo Backup and Restore Functions:
# - Dynamically loaded as a plug-in
# -----------------------------------------------------------------------------------------------------------------
export serverDataDirectory="/data/db"
function onBackupDatabase(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_backupFile=${2}
_hostname=$(getHostname ${_databaseSpec})
_database=$(getDatabaseName ${_databaseSpec})
_port=$(getPort ${_databaseSpec})
_portArg=${_port:+"--port=${_port}"}
_username=$(getUsername ${_databaseSpec})
_password=$(getPassword ${_databaseSpec})
echoGreen "Backing up '${_hostname}${_port:+:${_port}}${_database:+/${_database}}' to '${_backupFile}' ..."
_authDbArg=${MONGODB_AUTHENTICATION_DATABASE:+"--authenticationDatabase ${MONGODB_AUTHENTICATION_DATABASE}"}
mongodump -h "${_hostname}" -d "${_database}" ${_authDbArg} ${_portArg} -u "${_username}" -p "${_password}" --quiet --gzip --archive=${_backupFile}
return ${?}
)
}
function onRestoreDatabase(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_fileName=${2}
_adminPassword=${3}
_hostname=$(getHostname ${flags} ${_databaseSpec})
_database=$(getDatabaseName ${_databaseSpec})
_port=$(getPort ${flags} ${_databaseSpec})
_portArg=${_port:+"--port=${_port}"}
_username=$(getUsername ${_databaseSpec})
_password=$(getPassword ${_databaseSpec})
echo -e "Restoring '${_fileName}' to '${_hostname}${_port:+:${_port}}${_database:+/${_database}}' ...\n" >&2
# ToDo:
# - Add support for restoring to a different database.
# The following implementation only supports restoring to a database of the same name,
# unlike the postgres implementation that allows the database to be restored to a database of a different
# name for testing.
# Ref: https://stackoverflow.com/questions/36321899/mongorestore-to-a-different-database
_authDbArg=${MONGODB_AUTHENTICATION_DATABASE:+"--authenticationDatabase ${MONGODB_AUTHENTICATION_DATABASE}"}
mongorestore --drop -h ${_hostname} -d "${_database}" ${_authDbArg} ${_portArg} -u "${_username}" -p "${_password}" --gzip --archive=${_fileName} --nsInclude="*"
return ${?}
)
}
function onDatabaseInit() {
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
# Retrieve database details
_databaseSpec=${1}
_database=$(getDatabaseName "${_databaseSpec}")
_username=$(getUsername "${_databaseSpec}")
_password=$(getPassword "${_databaseSpec}")
# Check if the database already exists
result=$(mongosh --eval "db.getMongo().getDBNames().indexOf('$_database')")
if [ ! -z "$result" ] && [ "$result" -ge 0 ]; then
echoYellow "Database '$_database' already exists, skipping initialization."
return 0
fi
# Initialize the database by creating the user with the roles
mongosh "$_database" --quiet --eval "
db.createUser({
user: '$_username',
pwd: '$_password',
roles: [
{ role: 'dbOwner', db: '$_database' },
{ role: 'readWrite', db: '$_database' },
{ role: 'clusterAdmin', db: 'admin' }
]
});
" > /dev/null 2>&1 &
# Check the exit status of the createUser command
if [ $? -eq 0 ]; then
echoGreen "Database '$_database' initialized successfully."
return 0
else
echoRed "Failed to initialize database '$_database'."
return 1
fi
)
}
function onStartServer(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_hostname=$(getHostname ${flags} ${_databaseSpec})
# Start a local MongoDb instance
exec mongod --bind_ip $_hostname --quiet >/dev/null 2>&1 &
# Wait for mongodb to be ready
while ! mongosh --host $_hostname --eval "db.adminCommand('ping')" > /dev/null 2>&1; do
sleep 1
done
# Initialize database if necessary
onDatabaseInit "${_databaseSpec}"
)
}
function onStopServer(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_hostname=$(getHostname ${flags} ${_databaseSpec})
local startTime=$(date +%s%N)
local timeout=30
mongosh --host $_hostname --eval "db.getSiblingDB('admin').shutdownServer()" &
mongosh_pid=$!
# Wait for mongosh to finish or timeout
while kill -0 $mongosh_pid 2>/dev/null; do
if [ $(($(date +%s) - startTime)) -ge $timeout ]; then
kill $mongosh_pid
break
fi
sleep 1
done
# Ensure mongod is stopped
pkill -f "mongod --bind_ip $_hostname"
)
}
function onCleanup(){
(
if ! dirIsEmpty ${serverDataDirectory}; then
# Delete the database files and configuration
echo -e "Cleaning up ...\n" >&2
rm -rf ${serverDataDirectory}/*
else
echo -e "Already clean ...\n" >&2
fi
)
}
function onPingDbServer(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_hostname=$(getHostname ${flags} ${_databaseSpec})
mongosh --host $_hostname --eval "db.adminCommand('ping')" > /dev/null 2>&1
local mongoshExitCode=$?
if (( ${mongoshExitCode} != 0 )); then
return 1
else
return 0
fi
)
}
function onVerifyBackup(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_hostname=$(getHostname -l ${_databaseSpec})
_database=$(getDatabaseName ${_databaseSpec})
_port=$(getPort -l ${_databaseSpec})
_portArg=${_port:+"--port ${_port}"}
_username=$(getUsername ${_databaseSpec})
_password=$(getPassword ${_databaseSpec})
_dbAddressArg=${_hostname}${_port:+:${_port}}${_database:+/${_database}}
_authDbArg=${MONGODB_AUTHENTICATION_DATABASE:+"--authenticationDatabase ${MONGODB_AUTHENTICATION_DATABASE}"}
collections=$(mongosh ${_dbAddressArg} ${_authDbArg} -u "${_username}" -p "${_password}" --quiet --eval 'var dbs = [];dbs = db.getCollectionNames();for (i in dbs){ print(db.dbs[i]);}';)
rtnCd=${?}
# Get the size of the restored database
if (( ${rtnCd} == 0 )); then
size=$(getDbSize -l "${_databaseSpec}")
rtnCd=${?}
fi
if (( ${rtnCd} == 0 )); then
numResults=$(echo "${collections}"| wc -l)
if [[ ! -z "${collections}" ]] && (( numResults >= 1 )); then
# All good
verificationLog="\nThe restored database contained ${numResults} collections, and is ${size} in size."
else
# Not so good
verificationLog="\nNo collections were found in the restored database ${_database}."
rtnCd="3"
fi
fi
echo ${verificationLog}
return ${rtnCd}
)
}
function onGetDbSize(){
(
local OPTIND
local unset flags
while getopts : FLAG; do
case $FLAG in
? ) flags+="-${OPTARG} ";;
esac
done
shift $((OPTIND-1))
_databaseSpec=${1}
_hostname=$(getHostname ${flags} ${_databaseSpec})
_database=$(getDatabaseName ${_databaseSpec})
_port=$(getPort ${flags} ${_databaseSpec})
_portArg=${_port:+"--port ${_port}"}
_username=$(getUsername ${_databaseSpec})
_password=$(getPassword ${_databaseSpec})
_dbAddressArg=${_hostname}${_port:+:${_port}}${_database:+/${_database}}
_authDbArg=${MONGODB_AUTHENTICATION_DATABASE:+"--authenticationDatabase ${MONGODB_AUTHENTICATION_DATABASE}"}
size=$(mongosh ${_dbAddressArg} ${_authDbArg} -u "${_username}" -p "${_password}" --quiet --eval 'printjson(db.stats().fsTotalSize)')
rtnCd=${?}
echo ${size}
return ${rtnCd}
)
}
# =================================================================================================================