-
Notifications
You must be signed in to change notification settings - Fork 7
/
migrator
executable file
Β·504 lines (424 loc) Β· 16.3 KB
/
migrator
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2022-2023 CYBERTEC PostgreSQL International GmbH <[email protected]>
set -e
shopt -s nullglob
usage() {
print "$(cat <<EOF
$(highlight "up") Start Migrator in background
$(highlight "down") Stop Migrator
$(highlight "logs") Print logs
$(highlight "version") Display current version
$(highlight "versions") Display all sanctioned versions
$(highlight "update") Update version info from remote source
$(highlight "update") --archive <archive-file> Update version info from archive
$(highlight "upgrade") Upgrade to newest version
$(highlight "upgrade") --archive <archive-file> Upgrade to version contained in archive
$(highlight "upgrade") <version> Upgrade to specific version
$(highlight "configure <edition>") Generate settings file
$(highlight "configure --edition <edition>") Set CYBERTEC Migrator edition. Must be one of (assessment,trial,professional,enterprise)
$(highlight "configure --tls self-signed-cert") Generate self-signed TLS/SSL certificate
$(highlight "configure --tls cert:<file-location>") Install TLS/SSL certificate
$(highlight "configure --tls key:<file-location>") Install private key of TLS/SSL certificate
$(highlight "help") Display this help text
EOF
)"
}
# TODO use ERR_* constants instead of hard coded values
ERR_GENERAL=1
ERR_ARG=2
ERR_USAGE=3
dependency_barrier() {
command -v docker &>/dev/null || \
error "$(highlight "docker") not installed"
docker compose version &>/dev/null || \
error "$(highlight "docker compose") plugin not installed"
command -v git &>/dev/null || \
error "$(highlight "git") not installed"
}
# TODO: replace arguments with variables to make the code readable
main() {
catch_all_exit_code=1
case "${1}" in
up)
if ! is_tls_cert_configured; then
# || true to prevent exit with the error message so we can provide a suggestion
error "Could not find TLS/SSL certificate" || true
info "Run $(highlight "'${0} configure --tls self-signed-cert'") to generate a self-signed TLS/SSL certificate"
exit ${ERR_USAGE}
fi
fix_https_default_port
fix_encryption_key
docker compose up -d
print_url
;;
down)
docker compose down
;;
logs)
if [ ! -z "$(docker compose top)" ]; then
docker compose logs --timestamps --tail='all'
else
error "Logs not avaliable while not running ($(highlight "'${0} up'") to start)"
fi
;;
configure)
configure "$@"
;;
update)
update "$@"
;;
install)
;&
upgrade)
upgrade "$@"
;;
versions)
sanctioned_tags
;;
version)
if env_file_exists; then
print_env 'VERSION'
else
error "Initial configuration outstanding (run $(highlight "'${0} configure'"))"
fi
;;
help)
catch_all_exit_code='0'
;&
*)
error "Unknown command [${1}]" || true
usage
exit "${catch_all_exit_code}"
;;
esac
}
fix_https_default_port() {
# With v3.11.0 we switched from HTTP to HTTPS. In case the HTTP standard port
# is used, replace it with the standard HTTPS port.
# TODO: remove this function after a couple releases
if grep "^EXTERNAL_HTTP_PORT=80\s*$" ${ENV_FILE} &>/dev/null; then
sed -i'.orig' -e 's/^EXTERNAL_HTTP_PORT=80[ \t]*$/EXTERNAL_HTTP_PORT=443/' "${ENV_FILE}"
info "Changed port for web-frontend from HTTP to HTTPS"
fi
}
fix_encryption_key() {
# With v3.19.0, all passwords within the database are encrypted
# TODO: remove after a couple of releases
if [ -z "$(print_env 'CORE_ENCRYPTION_KEY')" ]; then
encryption_key="$(generate_random 'A-Za-z0-9' 32)"
encryption_iv="$(generate_random 'A-Za-z0-9' 16)"
echo "CORE_ENCRYPTION_KEY=\"${encryption_key}\"" >> "${ENV_FILE}"
echo "CORE_ENCRYPTION_IV=\"${encryption_iv}\"" >> "${ENV_FILE}"
info "Generated encryption key and IV"
fi
}
print_url() {
ip_addr="$(get_hostname)"
if [ ! -z "${ip_addr}" ]; then
port=":$(print_env 'EXTERNAL_HTTP_PORT')"
if [ "${port}" = ":${HTTPS_PORT_DEFAULT}" ]; then
port=''
fi
ok "Started on $(highlight "'https://${ip_addr}${port}'")"
fi
}
get_hostname() {
# BSD `hostname` doesn't understand the `-I` flag
(hostname --all-ip-addresses 2> /dev/null || hostname) | awk '{ print $1 }'
}
print_env() {
env -i "${BASH}" -c "set -a; . "${ENV_FILE}"; set +a; echo \${${1}};"
}
env_file_exists() {
[ -f "${ENV_FILE}" ]
}
configure() {
case "${2}" in
--edition)
edition=$(echo "${3}" | tr '[:upper:]' '[:lower:]')
verify_edition "$edition"
set_env_file_variable "EDITION" "$edition"
;;
--tls)
local tls_sub_command=$(echo "${3}" | cut --delimiter=":" --fields=1)
local tls_file_location=$(echo "${3}" | cut --delimiter=":" --fields=2)
case ${tls_sub_command} in
"")
error "Missing argument for option '${2}'"
;;
self-signed-cert)
generate_self_signed_certificate
;;
key)
exec_error=$(cp "${tls_file_location}" "${HOST_SSL_CERTIFICATE_KEY}" 2>&1 > /dev/null) || \
error "Failed to install TLS/SSL certificate key\n${exec_error}"
ok "Installed TLS/SSL certificate key"
;;
cert)
exec_error=$(cp "${tls_file_location}" "${HOST_SSL_CERTIFICATE}" 2>&1 > /dev/null) || \
error "Failed to install TLS/SSL certificate\n${exec_error}"
ok "Installed TLS/SSL certificate"
;;
*)
error "Unknown argument '${2} ${3}'"
;;
esac
;;
"")
error "Missing argument $(highlight "<edition>")"
;;
*)
edition=$(echo "${2}" | tr '[:upper:]' '[:lower:]')
verify_edition "$edition"
if generate_environment_file; then
./"${0}" configure --edition "$edition"
next_command="install"
installed_from_archive && next_command="${next_command} --archive <archive_file>"
info "Run $(highlight "'${0} ${next_command}'") to complete setup"
else
warn 'Environment file already exists'
info "Please modify environment file $(highlight "'${ENV_FILE}'") manually"
fi
;;
esac
}
generate_environment_file() {
# If file exists return false
! env_file_exists || return
# File doesn't exist, so generate it
password="$(generate_random 'A-Za-z0-9!&()*+,-./:;<=>?@{|}~' 32)"
encryption_key="$(generate_random 'A-Za-z0-9' 32)"
encryption_iv="$(generate_random 'A-Za-z0-9' 16)"
version="$(git describe --exact-match --tags HEAD)"
cat <<EOF > "${ENV_FILE}"
# ββ User configurable ββ
EXTERNAL_HTTP_PORT=${HTTPS_PORT_DEFAULT}
VERSION=${version}
EDITION=trial
# ββ Internal β ββ
CORE_DB_PASSWORD="${password}"
CORE_ENCRYPTION_KEY="${encryption_key}"
CORE_ENCRYPTION_IV="${encryption_iv}"
EOF
chmod 600 "${ENV_FILE}"
ok 'Generated environment file'
}
set_env_file_variable() {
if grep "^$1=.*$" "${ENV_FILE}" &>/dev/null; then
sed -i -e "s/^$1=.*$/$1=$2/" "${ENV_FILE}"
else
sed -i "1{G;s/$/$1=$2/}" "${ENV_FILE}"
fi
}
generate_random() {
local PASSWORD_CHARSET="$1"
local PASSWORD_LENGTH=$2
LC_ALL=C tr -dc "${PASSWORD_CHARSET}" </dev/urandom | head -c "${PASSWORD_LENGTH}"
}
# TODO Switch to .meta-inf file which contains more information. For now we
# remain on the .version file for backwards compatibility.
installed_from_archive() {
[ -f "${VERSION_FILE}" ] && return
false
}
generate_self_signed_certificate() {
info "Generating self-signed TLS/SSL certificate"
docker compose run --no-deps web_gui \
openssl req -x509 -nodes -newkey rsa:2048 \
-keyout "${NGINX_SSL_CERTIFICATE_KEY}" -out "${NGINX_SSL_CERTIFICATE}"
docker compose run --no-deps web_gui \
chown $UID:$(id -g) "${NGINX_SSL_CERTIFICATE_KEY}" "${NGINX_SSL_CERTIFICATE}"
ok "Generated self-signed TLS/SSL certificate"
next_step_upgrade
}
update() {
# No archive provided β Fetch from origin
if [ -z "${2}" ]; then
info 'Updating release information'
git fetch || error 'Could not fetch versions'
new_version=$(most_recent_tag)
info "Recommended version: "$(highlight "${new_version}")""
info "Run $(highlight "'${0} upgrade'") to upgrade to version ${new_version}"
# Archive provided β Use `.git` folder contained within archive as origin
elif [ "${2}" = '--archive' ] && [ -f "${3}" ]; then
info "Updating release information from archive '${3}'"
temp_dir="$(mktemp -t "${TEMP_TEMPLATE}" -d)"
trap 'rm -rf -- "${temp_dir}"' EXIT
extract_error=$(tar -xf "${3}" --strip-components=2 --directory "${temp_dir}" "${ARCHIVE_DIR}/${VERSION_FILE}" "${ARCHIVE_DIR}/.git" 2>&1 > /dev/null) || \
error "Failed to extract update information\n${extract_error}"
archive_version=$(<"${temp_dir}/${VERSION_FILE}")
git fetch --quiet --tags "${temp_dir}/.git" 1>/dev/null
info "Updated release information"
info "Run $(highlight "'${0} upgrade --archive ${3}'") to upgrade to version ${archive_version}"
else
error "Invalid path $(highlight "${3}")"
fi
}
most_recent_tag() {
sanctioned_tags | head -n 1
}
sanctioned_tags() {
git tag --sort=-v:refname
}
upgrade() {
# Provide the means to upgrade to a specific version. Needed if we want to
# install to an older version than the current one. Especially usefule for
# testing.
[ generate_environment_file ] || true
# No parameters provided β Fetch most recent images from online registry
if [ -z "${2}" ]; then
version="$(most_recent_tag)"
edition=$(print_env 'EDITION')
if [ -z "${version}" ]; then
error "No versions available (run $(highlight "'${0} update'") to fetch versions)"
fi
edition_barrier
info "Pulling images for $(highlight "${edition}:${version}")"
if pull_error=$(VERSION="${version}" EDITION="${edition}" docker compose pull 2>&1 > /dev/null); then
ok "Pulled $(highlight "${edition}:${version}")"
elif installed_from_archive; then
# || true to prevent exit with the error message so we can provide a suggestion
error "Failed to pull container images\n${pull_error}\n" || true
info "Migrator was extracted from archive file: run $(highlight "'${0} ${1} --archive <archive_file>'") to proceed with upgrade"
exit 2
else
error "Failed to pull container images\n${pull_error}"
fi
# Archive provided β Import images from archive
elif [ "${2}" = '--archive' ] && [ -f "${3}" ]; then
# TODO move reading version incl. version check to a function
info "Reading meta-information from archive file '${3}'"
version=$(tar -xf "${3}" "${ARCHIVE_DIR}/${VERSION_FILE}" --to-stdout 2>&1) || \
error "Failed to extract archive file\n$version"
edition=$(tar -xf "${3}" "${ARCHIVE_DIR}/${EDITION_FILE}" --to-stdout 2>&1) || \
error "Failed to extract archive file\n$edition"
version_barrier "${version}" || (
info "Run $(highlight "'${0} update --archive ${3}'") before attempting upgrade"
exit 1
)
info "Upgrading to $edition:$version"
info "Extracting archive file '${3}'"
temp_dir="$(mktemp -t "${TEMP_TEMPLATE}" -d)"
trap 'rm -rf -- "${temp_dir}"' EXIT
extraction_error=$(tar -xf "${3}" --strip-components=2 --directory "${temp_dir}" 2>&1 > /dev/null) || \
error "Failed to extract archive file\n$extraction_error"
archive_image_path="${temp_dir}/${IMAGE_PATH}"
[ -d "${archive_image_path}" ] || error "Archive file corrupted - '${IMAGE_PATH}' directory with container images missing"
# Import images *before* moving them to local image directory
info 'Loading container images'
for image in ${archive_image_path}/*.tar; do
docker load < "${image}"
done
info 'Container images loaded'
# Save loaded images from the archive file.
mkdir -p "${IMAGE_PATH}"
mv ${archive_image_path}/*.tar "${IMAGE_PATH}"
info 'Archived container images'
# Save the edition in the .env file.
set_env_file_variable EDITION "${edition}"
# Explicit version provided but no archive
elif [ ! -z "${2}" ] && [ -z "${3}" ]; then
version_barrier "${2}"
edition_barrier
version="${2}"
edition=$(print_env 'EDITION')
info "Pulling $(highlight "${edition}:${version}")"
VERSION="${version}" EDITION="${edition}" docker compose pull
ok "Pulled $(highlight "${edition}:${version}")"
else
error 'Unexpected usage'
fi
git checkout --quiet "${version}"
replace_in_place "s/^VERSION=.*/VERSION=${version}/" "${ENV_FILE}"
edition=$(print_env 'EDITION')
info "Upgraded to $(highlight "${edition}:${version}")"
if is_tls_cert_configured; then
next_step_upgrade
else
warn "Could not find TLS/SSL certificate"
info "Run $(highlight "'${0} configure --tls self-signed-cert'") to generate a self-signed TLS/SSL certificate"
fi
}
version_barrier() {
if ! git tag | grep -q "^${1}$"; then
error "Unknown version $(highlight "${1}")"
fi
}
edition_barrier() {
edition=$(print_env 'EDITION')
if [ -z "${edition}" ]; then
error "No edition specified. Run $(highlight "'${0} configure --edition <edition>'") to continue"
fi
}
verify_edition() {
edition="${1}"
if [ "$edition" != "assessment" ] \
&& [ "$edition" != "trial" ] \
&& [ "$edition" != "professional" ] \
&& [ "$edition" != "enterprise" ]; then
error "Edition $(highlight "'$edition'") is invalid. Possible values: assessment,trial,professional,enterprise"
fi
}
# TODO: replace this with sed -I
replace_in_place() {
target=$(mktemp)
sed -e "${1}" "${2}" > "${target}"
mv "${target}" "${2}"
}
is_tls_cert_configured() {
[ -f "${HOST_SSL_CERTIFICATE}" -a -f "${HOST_SSL_CERTIFICATE_KEY}" ]
}
next_step_upgrade() {
info "Run $(highlight "'${0} up'") to switch to new version"
warn 'Switching will abort running migrations'
}
# Color codes
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
WHITE='\033[1;37m'
LIGHT_GREY='\033[1;37m'
# No color
NC='\033[0m'
print() {
printf "${1}\n"
}
highlight() {
echo "${LIGHT_GREY}${1}${NC}"
}
error() {
>&2 printf "[${RED}ERROR${NC}] ${1}\n"
return ${2-1}
}
warn() {
printf "[${YELLOW}WARN${NC}] ${1}\n"
}
info() {
printf "[${WHITE}INFO${NC}] ${1}\n"
}
ok() {
printf "[${GREEN}OK${NC}] ${1}\n"
}
HTTPS_PORT_DEFAULT=443
# Temporary directory
TEMP_TEMPLATE='migrator.XXXXXX'
# Directory name in archive
ARCHIVE_DIR='./cybertec_migrator'
# Environment configuration files
ENV_FILE='./.env'
# Directory where we save container images provided from offline installation packages
IMAGE_PATH='images'
# These files exist only if the directory was provided by on offline installation package
EDITION_FILE='.edition'
VERSION_FILE='.version'
# TLS/SSL files location defined in the nginx.conf (in the container)
NGINX_SSL_CERTIFICATE=/etc/nginx/certs/nginx.crt
NGINX_SSL_CERTIFICATE_KEY=/etc/nginx/certs/nginx.key
# TLS/SSL file on host (local bind mounts)
HOST_SSL_CERTIFICATE=${NGINX_SSL_CERTIFICATE/"/etc"/"./volumes/web_gui"}
HOST_SSL_CERTIFICATE_KEY=${NGINX_SSL_CERTIFICATE_KEY/"/etc"/"./volumes/web_gui"}
dependency_barrier
# Change working directory to directory that contains script
cd "${0%/*}"
main "$@"