-
Notifications
You must be signed in to change notification settings - Fork 1
/
osinstancectl.sh
executable file
·3080 lines (2895 loc) · 101 KB
/
osinstancectl.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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Manage dockerized OpenSlides instances
#
# -------------------------------------------------------------------
# Copyright (C) 2019 by Intevation GmbH
# Author(s):
# Gernot Schulz <gernot@intevation.de>
# Adrian Richter <adrian@intevation.de>
#
# This program is distributed under the MIT license, as described
# in the LICENSE file included with the distribution.
# SPDX-License-Identifier: MIT
# -------------------------------------------------------------------
set -eu
set -o noclobber
set -o pipefail
# Defaults (override in $CONFIG)
INSTANCES="/srv/openslides/os4-instances"
COMPOSE_TEMPLATE=
CONFIG_YML_TEMPLATE="/etc/osinstancectl.d/config.yml.template"
HOOKS_DIR=
MANAGEMENT_TOOL_BINDIR="/usr/local/lib/openslides-manage/versions"
HAPROXYCFG="/etc/haproxy/haproxy.cfg"
# Legacy instances path
OS3_INSTANCES="/srv/openslides/docker-instances"
# constants
CONFIG="/etc/osinstancectl.d/os4instancectlrc"
ME=$(basename -s .sh "${BASH_SOURCE[0]}")
PIDFILE="/tmp/osinstancectl.pid"
MARKER=".osinstancectl-marker"
LOCKFILE=".osinstancectl-locks"
DEFAULT_MANAGEMENT_VERSION=latest
MANAGEMENT_TOOL="${MANAGEMENT_TOOL_BINDIR}/${DEFAULT_MANAGEMENT_VERSION}"
ADMIN_SECRETS_FILE="superadmin"
USER_SECRETS_FILE="user.yml"
DB_SECRETS_FILE="postgres_password"
MANAGEMENT_BACKEND=backendManage
MIGRATIONS_STATUS_NOT_REQ=no_migration_required
MIGRATIONS_STATUS_REQ=migration_required
MIGRATIONS_STATUS_FIN_REQ=finalization_required
MIGRATIONS_STATUS_RUN=migration_running
CURL_OPTS=(--max-time 1 --retry 2 --retry-delay 1 --retry-max-time 3)
ALLOWED_LOCK_ACTIONS="autoscale clone erase remove start stop update"
# global variables
PROJECT_NAME=
PROJECT_DIR=
PROJECT_STACK_NAME=
PORT=
DEPLOYMENT_MODE=
MODE=
USAGE=
DOCKER_IMAGE_TAG_OPENSLIDES=
OPT_MIGRATIONS_FINALIZE=
OPT_MIGRATIONS_ASK=1
OPT_ADD_ACCOUNT=1
OPT_DRY_RUN=
OPT_FAST=
OPT_FORCE=
OPT_JSON=
OPT_LOCALONLY=
OPT_LOCK_ACTION=()
OPT_LOG=${OPT_LOG:-1}
OPT_LONGLIST=
OPT_MANAGEMENT_TOOL=
OPT_METADATA=
OPT_METADATA_SEARCH=
OPT_PATIENT=
OPT_PIDFILE=1
OPT_SECRETS=
OPT_SERVICES=
OPT_STATS=
OPT_USE_PARALLEL="${OPT_USE_PARALLEL:-1}"
OPT_VERBOSE=0
FILTER_RUNNING_STATE=
FILTER_LOCKED_STATE=
FILTER_VERSION=
CLONE_FROM=
LEGAL_NOTICE_FILE=
PRIVACY_POLICY_FILE=
OPENSLIDES_USER_FIRSTNAME=
OPENSLIDES_USER_LASTNAME=
OPENSLIDES_USER_EMAIL=
OPENSLIDES_USER_PASSWORD=
OPT_PRECISE_PROJECT_NAME=
HAS_DOCKER_ACCESS=
HAS_MANAGEMENT_ACCESS=
# Scale related
declare -A SCALE_FROM=()
declare -A SCALE_TO=()
declare -A SCALE_RUNNING=()
MEETINGS_TODAY=
ACCOUNTS_TODAY=
ACCOUNTS=
AUTOSCALE_ACCOUNTS_OVER=
AUTOSCALE_RESET_ACCOUNTS_OVER=
# Color and formatting settings
OPT_COLOR=auto
NCOLORS=
COL_NORMAL=""
COL_RED=""
COL_YELLOW=""
COL_GREEN=""
BULLET='●'
SYM_NORMAL="OK"
SYM_ERROR="XX"
SYM_UNKNOWN="??"
SYM_STOPPED="__"
JQ="jq --monochrome-output"
DEPS=(
docker
gawk
jq
nc
yq
)
enable_color() {
NCOLORS=$(tput colors) # no. of colors
if [[ -n "$NCOLORS" ]] && [[ "$NCOLORS" -ge 8 ]]; then
COL_NORMAL="$(tput sgr0)"
COL_RED="$(tput setaf 1)"
COL_YELLOW="$(tput setaf 3)"
COL_GREEN="$(tput setaf 2)"
COL_GRAY="$(tput bold; tput setaf 0)"
JQ="jq --color-output"
fi
}
usage() {
cat <<EOF
Usage: $ME [options] <action> <instance|pattern>
Manage OpenSlides Docker instances.
Actions:
ls List instances and their status. <pattern> is
a grep ERE search pattern in this case. For details on
the output format, see below.
add Add a new instance for the given domain (requires FQDN)
rm Remove <instance> (requires FQDN)
start Start, i.e., (re)deploy an existing instance
stop Stop a running instance
update Update OpenSlides services to a new version
erase Execute the mid-erase hook without otherwise removing
the instance.
lock Put a lock on the instance which prohibits one or more
actions from being executed for the instance.
unlock Remove locks from an instance.
autoscale Scale relevant services of an instance based on it's
meetings dates and users. Will only scale down if there
no meeting scheduled for today.
(adjust values in CONFIG file)
manage Call the openslides-manage tool on an instance.
See the tool's help message for details on its usage.
All args ond opts that are to be passed to the tool
should be stated after a '--'.
If the management command is more than one word it must be
quoted, e.g. 'migrations stats'.
setup Run basic setup steps for $ME interactively.
help <action> Print detailed usage information for the given action.
Options:
-d,
--project-dir=DIR Directly specify the project directory
--compose-template=FILE Specify the docker-compose YAML template
--config-template=FILE Specify the config.yml template
--force Disable various safety checks
--color=WHEN Enable/disable color output. WHEN is never, always, or
auto.
--verbose Increase output verbosity (may be repeated)
--help Display this help message and exit
EOF
case "${HELP_TOPIC:-}" in
list)
cat << EOF
for ls:
-a, --all Equivalent to --long --secrets --metadata --services
--stats
-l, --long Include more information in extended listing format
-s, --secrets Include sensitive information such as login credentials
-m, --metadata Include metadata in instance list
--services Include list of services in instance list
--stats Include addtional information from running instances,
e.g., meetings details
-n, --online Show only online instances
-f, --offline Show only stopped instances
-e, --error Show only running but unreachable instances
--locked Show only locked instances (see \`lock\`/\`unlock\` modes)
--unlocked Show only unlocked instances (see \`lock\`/\`unlock\` modes)
-M,
--search-metadata Include metadata
--fast Include less information to increase listing speed
--patient Increase timeouts
--version=REGEXP Filter results based on the version reported by
\`$ME ls\` (not --long; implies --online).
-j, --json Enable JSON output format
The ls output:
The columnar output lists each instance's status, name, version(s) and
an optional comment.
Colored status indicators:
green The instance appears to be fully functional
red The instance is running but is unreachable
yellow The instance's status can not be determined
gray The instance has been stopped
Version information in ls mode:
Both the instances own version string (simple) as well as the container
image versions (complex) can be displayed. The available information
depends on the user's access permissions to Docker.
- Complex: This version is based on the Docker image versions actually in
use. Normally, this is a single tag; however, in case there is more than
one tag in use, the display format is extended to include more detail.
It lists each tag with the number of containers running this tag,
separated by slashes, as well as a final sum of the number of different
registries and tags in square brackets, e.g., "[1:2]". In the --long
output format this version is listed as "Version". If available, it
takes precedence over the simple version string and is used for the
compact ls output.
- Simple: This version simply reports the version string that has been
built into the image. It is available under most circumstances. In the
--long output format, it is listed as "Version (image)" (and also as
"Version" if the complex version string is unavailable).
Stats in ls mode:
- Meetings: active/max. number of meetings
- List of meetings: ID, name, dates, Jitsi configuration of each meeting
- Users: active/total/max. number of users
EOF
;;
start)
cat << EOF
for start:
-O, --management-tool=[PATH|NAME|*|-]
Specify the 'openslides' executable to use. The program
must be available in the management tool's versions
directory [${MANAGEMENT_TOOL_BINDIR}/].
If only a file NAME is given, it is assumed to be
relative to that directory.
The special string "*" indicates that no version is to
be recorded which will always cause the latest version
to be selected. The special string "-" indicates that
the version is to remain unchanged.
[Default: ${DEFAULT_MANAGEMENT_VERSION}]
--migrations-finalize Immediately finalize required migrations and do the
full instance update as soon as possible.
--migrations-no-ask Do not ask for confirmations when handling migrations.
EOF
;;
create | update)
cat << EOF
for add & update:
-t, --tag=TAG Specify the default image tag for all OpenSlides
components (defaults.tag).
-O, --management-tool=[PATH|NAME|*|-]
Specify the 'openslides' executable to use. The program
must be available in the management tool's versions
directory [${MANAGEMENT_TOOL_BINDIR}/].
If only a file NAME is given, it is assumed to be
relative to that directory.
The special string "*" indicates that no version is to
be recorded which will always cause the latest version
to be selected. The special string "-" indicates that
the version is to remain unchanged.
[Default: ${DEFAULT_MANAGEMENT_VERSION}]
--local-only Create an instance without setting up HAProxy and Let's
Encrypt certificates. Such an instance is only
accessible on localhost, e.g., http://127.0.0.1:61000.
--migrations-finalize Immediately finalize required migrations and do the
full instance update as soon as possible.
--migrations-no-ask Do not ask for confirmations when handling migrations.
--no-add-account Do not add an additional, customized local admin account.
--clone-from Create the new instance based on the specified existing
instance.
EOF
;;
autoscale)
cat << EOF
for autoscale:
--accounts=NUM Specify the number of accounts to scale for overriding
read from metadata.txt
--dry-run Print out actions instead of actually performing them
EOF
;;
lock | unlock)
cat << EOF
for lock & unlock:
--action=ACTION Specify a specific action to lock instead of all
actions. Available actions are:
${ALLOWED_LOCK_ACTIONS}
EOF
;;
*)
cat << EOF
Use $ME help <action> for details.
EOF
;;
esac
}
fatal() {
echo 1>&2 "${COL_RED}ERROR${COL_NORMAL}: $*"
exit 23
}
warn() {
echo 1>&2 "${COL_RED}WARN${COL_NORMAL}: $*"
}
info() {
echo 1>&2 "${COL_GREEN}INFO${COL_NORMAL}: $*"
}
verbose() {
local lvl=$1
shift
[[ "$OPT_VERBOSE" -ge 1 ]] || return 0
[[ "$lvl" -le "$OPT_VERBOSE" ]] || return 0
echo 1>&2 "${COL_GREEN}DEBUG${lvl}${COL_NORMAL}: $*"
}
tag_output() {
local prefix=${1:-EXT}
stdbuf -oL sed "s/^/${COL_YELLOW}${prefix}${COL_NORMAL}: /"
}
clean_up() {
# Clean up the PID file (only if it is this process' own PID file)
local pid logname email
if [[ -f "$PIDFILE" ]] && read -r pid logname email < "$PIDFILE" && [[ $pid -eq $$ ]]
then
# Truncate file; should always work (has mode 666)
>| "$PIDFILE"
# Delete file; may fail if it is a stale file created by another user
rm -f "$PIDFILE" >/dev/null 2>&1 || true
fi
}
create_and_check_pid_file() {
# Create PID file in /tmp/, so all users may create them without requiring
# any additional measures, e.g., for /var/run/. The sticky bit commonly set
# on /tmp/ requires the PID file mechanism to handle circumstances in which
# even a stale file can not be removed.
local pid logname email by message
if [[ -f "$PIDFILE" ]]; then
read -r pid logname email < "$PIDFILE"
by=$logname
[[ -z "$email" ]] || by="${logname} [${email}]"
message="$ME is already being executed by ${by} (PID: ${pid}, PID file: ${PIDFILE})"
if ps p "$pid" >/dev/null 2>&1; then
if [[ -n "$OPT_PIDFILE" ]]; then
fatal "$message"
else
warn "$message"
warn "continuing anyways (--no-pid-file)"
fi
else
warn "Stale PID file detected."
if [[ -n "$OPT_PIDFILE" ]]; then
warn "overwriting"
else
warn "ignoring (--no-pid-file)"
fi
fi
elif [[ -z "$OPT_PIDFILE" ]]; then
return 0
else
# Create the file and allow other users to update it
touch "$PIDFILE"
chmod 666 "$PIDFILE"
fi
echo "$$ ${LOGNAME:-"unknown"} ${EMAIL:-}" >| "$PIDFILE"
}
check_for_dependency () {
[[ -n "$1" ]] || return 0
command -v "$1" > /dev/null
}
arg_check() {
case "$MODE" in
# Mode-dependent dependency check
"setup") :;;
*)
for i in "${DEPS[@]}"; do
check_for_dependency "$i" || fatal "Dependency not found: $i"
done
;;
esac
[[ -d "$INSTANCES" ]] || { fatal "$INSTANCES not found!"; }
# Commands that work without a specific instance argument
case "$MODE" in
"list") :;;
*)
[[ -n "$PROJECT_NAME" ]] || { fatal "Please specify a project name"; return 2; }
;;
esac
case "$MODE" in
"start" | "stop" | "remove" | "erase" | "update" | "autoscale" | "create")
[[ "$HAS_DOCKER_ACCESS" ]] ||
fatal "User $USER does not have access to the Docker daemon. See \`docker info\`."
;;
esac
case "$MODE" in
"start" | "stop" | "remove" | "erase" | "update" | "autoscale" | "manage" | "lock" | "unlock")
[[ -d "$PROJECT_DIR" ]] || {
fatal "Instance '${PROJECT_NAME}' not found."
}
[[ -f "${DCCONFIG}" ]] || {
fatal "Not a ${DEPLOYMENT_MODE} instance."
}
;;
esac
case "$MODE" in
"create" | "clone")
[[ ! -d "$PROJECT_DIR" ]] || {
fatal "Instance '${PROJECT_NAME}' already exists."
}
[[ ! -d "${OS3_INSTANCES}/${PROJECT_NAME}" ]] || {
fatal "Instance '${PROJECT_NAME}' already exists as an OpenSlides 3 instance."
}
;;
esac
case "$MODE" in
"clone")
[[ -d "$CLONE_FROM_DIR" ]] || {
fatal "$CLONE_FROM_DIR does not exist."
}
;;
esac
case "$MODE" in
"lock" | "unlock")
for i in "${OPT_LOCK_ACTION[@]}"; do
grep -qw "$i" <<< "$ALLOWED_LOCK_ACTIONS" ||
fatal "Unknown action: ${i}."
done
esac
}
log_output() {
dir=$1
if [[ "$OPT_LOG" -eq 1 ]]; then
mkdir -p "${dir}/log"
tee "${dir}/log/${MODE}-$(date "+%F.%s").log"
else
cat -
fi
}
marker_check() {
[[ -f "${1}/${MARKER}" ]] || {
fatal "The instance was not created with $ME."
return 1
}
}
self_setup() {
local setup_with_errors=0
local n=0
check_ok() {
echo " ${COL_GREEN}✓${COL_NORMAL} $*"
}
check_fail() {
echo " ${COL_RED}✗${COL_NORMAL} $*"
setup_with_errors=1
}
printf "\n——— $ME setup assistant ———\n\n"
cat << EOF | tr '\n' ' ' | fold -s
This command assists you in creating the basic setup required for OpenSlides 4
deployments with $ME. Please note, however, that this is not a fully automated
setup procedure and that additional steps will be required.
EOF
printf '\n\n'
[[ ! -f "$CONFIG" ]] || {
info "Applying settings from $CONFIG."
echo
}
echo " $((++n)). Checking dependencies"
for i in "${DEPS[@]}"; do
if check_for_dependency "$i"; then
check_ok "Found: $i"
else
check_fail "Not found: $i"
fi
done
#
printf "\n $((++n)). Checking permissions\n"
[[ "$LOGNAME" = root ]] ||
check_fail "Not running as root. root privileges are usually required."
if [[ "$HAS_DOCKER_ACCESS" ]]; then
check_ok "Docker access succeeded."
# Check if Swarm has been set up
if docker node inspect self >/dev/null 2>&1; then
check_ok "Docker Swarm is set up."
else
check_fail "Docker Swarm is not set up which is required for $ME."
fi
else
check_fail "You don't have access to docker."
fi
#
printf "\n $((++n)). Checking directories\n"
if [[ -d "$INSTANCES" ]]; then
check_ok "The instance directory ${INSTANCES}/ exists."
else
check_fail "The instance directory '${INSTANCES}/' does not exist."
read -p " → Create it now? [y/N] "
case "$REPLY" in
Y|y|Yes|yes|YES) mkdir -pm 750 "$INSTANCES";;
esac
fi
#
printf "\n $((++n)). Checking $ME configuration\n"
if [[ -f "$CONFIG_YML_TEMPLATE" ]]; then
check_ok "Found configuration template file $CONFIG_YML_TEMPLATE."
else
check_fail "Configuration template $CONFIG_YML_TEMPLATE not found."
read -p " → Create a minimal template now? [y/N] "
case "$REPLY" in
Y|y|Yes|yes|YES)
create_config_template || setup_with_errors=1 ;;
esac
fi
#
printf "\n $((++n)). Checking external OpenSlides management tool\n"
if [[ -x "$MANAGEMENT_TOOL" ]]; then
check_ok "The 'openslides' management tool is installed ($MANAGEMENT_TOOL)."
else
check_fail "The management tool is not installed."
local bin_installer=openslides-bin-installer
# If openslides-bin-installer is installed or available next to $ME
if command -v $bin_installer >/dev/null || {
bin_installer="$(dirname "${BASH_SOURCE[0]}")/${bin_installer}.sh"
[[ -x "$bin_installer" ]]
}
then
echo
echo " → Install the managment tool now? $bin_installer will download" \
"the compiled program from GitHub."
echo " Hint: See \`$bin_installer --help\` for the download URL and" \
"other methods of installing 'openslides'."
read -p " Continue? [y/N] "
case "$REPLY" in
Y|y|Yes|yes|YES)
echo
"$bin_installer" --quiet |& tag_output "install" && setup_with_errors=0
;;
esac
else
check_fail "Could not find openslides-bin-installer to automatically install the 'openslides' tool."
echo
echo " → Hint: Please install openslides-bin-installer and use it to install the 'openslides' binary."
fi
fi
#
printf "\n $((++n)). Checking HAProxy setup\n"
if [[ -w "$HAPROXYCFG" ]]; then
check_ok "Found writable ${HAPROXYCFG}."
if grep -qF -- "-----BEGIN AUTOMATIC OPENSLIDES CONFIG-----" "$HAPROXYCFG" &&
grep -qF -- "-----END AUTOMATIC OPENSLIDES CONFIG-----" "$HAPROXYCFG"
then
check_ok "${HAPROXYCFG} has been set up for $ME."
else
check_fail "${HAPROXYCFG} has not been set up for $ME yet."
echo
echo " → Hint: See haproxy.cfg.example in the repository for an example configuration."
fi
else
check_fail "${HAPROXYCFG} not found or writeable."
echo
echo " → Hint: See haproxy.cfg.example in the repository for an example configuration."
echo " Alternatively, you may create instances with the --local-only option."
fi
#
printf "\n——— RESULT ———\n"
if [[ "$setup_with_errors" -eq 0 ]]; then
echo "Congratulations, your system meets the basic prerequisites!"
else
echo "Unfortunately, not all prerequisites have been met. " \
"Running $ME without resolving the issues may fail."
fi
echo
}
hash_management_tool() {
# Return the SHA256 hash of the selected "openslides" tool. For lack of
# proper versioning, the hash is used to track compatibility with individual
# instances by adding it to each config.yml.
sha256sum "$MANAGEMENT_TOOL" 2>/dev/null | gawk '{ print $1 }' ||
fatal "$MANAGEMENT_TOOL not found."
}
select_management_tool() {
# Read the required management tool version from the instance's config file
# or use the version provided on the command line.
local pdir
# Find/configure the correct instance directory
if [[ $# -eq 0 ]]; then
pdir=$PROJECT_DIR
elif [[ $# -eq 1 ]]; then
pdir=$1
else
fatal "Wrong number of argumnts for select_management_tool()"
fi
MANAGEMENT_TOOL_HASH=
if [[ -n "$OPT_MANAGEMENT_TOOL" ]]; then
verbose 2 "Selecting management tool based on option: ${OPT_MANAGEMENT_TOOL}."
# The given argument is the special string "-", indicating that the version
# should remain unchanged
if [[ "$OPT_MANAGEMENT_TOOL" = '-' ]]; then
MANAGEMENT_TOOL_HASH=$(value_from_config_yml "$pdir" '.managementToolHash')
# Resolve the '*' to latest
[[ "$MANAGEMENT_TOOL_HASH" != '*' ]] ||
MANAGEMENT_TOOL_HASH="$DEFAULT_MANAGEMENT_VERSION"
MANAGEMENT_TOOL="${MANAGEMENT_TOOL_BINDIR}/${MANAGEMENT_TOOL_HASH}"
# The given argument is the special string "*", indicating that the latest
# version should be followed
elif [[ "$OPT_MANAGEMENT_TOOL" = '*' ]]; then
MANAGEMENT_TOOL="${MANAGEMENT_TOOL_BINDIR}/${DEFAULT_MANAGEMENT_VERSION}"
elif [[ "$OPT_MANAGEMENT_TOOL" =~ \/ ]]; then
# The given argument is a path
MANAGEMENT_TOOL=$(realpath "$OPT_MANAGEMENT_TOOL")
else
# The given argument is only a filename; prepend path here
MANAGEMENT_TOOL="${MANAGEMENT_TOOL_BINDIR}/${OPT_MANAGEMENT_TOOL}"
fi
# Reading tool version from instance configuration
elif MANAGEMENT_TOOL_HASH=$(value_from_config_yml "$pdir" '.managementToolHash'); then
verbose 2 "Selecting management tool based on instance configuration:" \
"${MANAGEMENT_TOOL_HASH}."
# Version is set to simply follow latest
if [[ "$MANAGEMENT_TOOL_HASH" = '*' ]]; then
MANAGEMENT_TOOL="${MANAGEMENT_TOOL_BINDIR}/latest"
# Version is configured to a specific hash
else
MANAGEMENT_TOOL="${MANAGEMENT_TOOL_BINDIR}/${MANAGEMENT_TOOL_HASH}"
fi
fi
MANAGEMENT_TOOL_HASH=$(hash_management_tool)
[[ -x "$MANAGEMENT_TOOL" ]] || fatal "$MANAGEMENT_TOOL not found."
verbose 1 "Using management tool ${MANAGEMENT_TOOL}."
}
call_manage_tool() {
[[ "$#" -ge 1 ]] ||
fatal "Insufficient parameters to call management tool."
[[ "$#" -ge 2 ]] ||
fatal "Missing command for management tool."
local opts=
local dir="$1"
local cmd="$2"
shift 2
local args="$@"
case "$cmd" in
# non-applicable commands, call without default opts
config-create-default | help )
break
;;
# management commands that don't connect to the 'manage' service and,
# instead, operate in PROJECT_DIR
setup | config )
local template= config= localconfig=
[[ ! -r "$COMPOSE_TEMPLATE" ]] ||
template="--template=${COMPOSE_TEMPLATE}"
[[ ! -r "$CONFIG_YML_TEMPLATE" ]] ||
config="--config=${CONFIG_YML_TEMPLATE}"
[[ ! -r "${PROJECT_DIR}/config.yml" ]] ||
localconfig="--config=${PROJECT_DIR}/config.yml"
opts="$template $config $localconfig $dir"
;;
# all other commands are assumed to connect to the 'manage' service
*)
local port=$(value_from_config_yml "$dir" '.port')
local secret="${dir}/secrets/manage_auth_password"
# The manage tool can't connect to the 'manage' service without access to
# the secret.
[[ -r "$secret" ]] || return 1
opts="-a 127.0.0.1:${port} --password-file $secret --no-ssl"
;;
esac
verbose 2 "Executing $MANAGEMENT_TOOL $cmd $opts $args"
$MANAGEMENT_TOOL $cmd $opts $args || return $?
}
next_free_port() {
# Select new port
#
# This parses existing instances' YAML files to discover used ports and to
# select the next one. Other methods may be more suitable and robust but
# have other downsides. For example, `docker-compose port client 80` is
# only available for running services.
local HIGHEST_PORT_IN_USE
local PORT
HIGHEST_PORT_IN_USE=$(
{
# OS3 instance ports
if [[ -d "${OS3_INSTANCES}" ]]; then
find "${OS3_INSTANCES}" -type f -name ".env" -print0 |
xargs -0 --no-run-if-empty grep -h "EXTERNAL_HTTP_PORT" |
cut -d= -f2 | tr -d \"\'
fi
# OS4 instance ports
find "${INSTANCES}" -type f -name "config.yml" -print0 |
xargs -0 --no-run-if-empty yq --no-doc eval '.port'
} | sort -rn | head -1
)
[[ -n "$HIGHEST_PORT_IN_USE" ]] || HIGHEST_PORT_IN_USE=61000
PORT=$((HIGHEST_PORT_IN_USE + 1))
# Check if port is actually free
# try to find the next free port (this situation can occur if there are test
# instances outside of the regular instances directory)
n=0
while ! ss -tnHl | gawk -v port="$PORT" '$4 ~ port { exit 2 }'; do
[[ $n -le 25 ]] || { fatal "Could not find free port"; }
((PORT+=1))
[[ $PORT -le 65535 ]] || { fatal "Ran out of ports"; }
((n+=1))
done
echo "$PORT"
}
value_from_config_yml() {
local instance target result
instance="$1"
target="$2"
result=null
if [[ -f "${instance}/config.yml" ]]; then
result=$(yq eval $target "${instance}/config.yml")
fi
if [[ "$result" == "null" ]]; then
if [[ -f "${CONFIG_YML_TEMPLATE}" ]]; then
result=$(yq eval $target "${CONFIG_YML_TEMPLATE}")
fi
fi
[[ "$result" != "null" ]] || return 1
echo "$result"
}
update_config_yml() {
local file=$1
local expr=$2
[[ -f "$file" ]] || touch "$file"
yq eval -i "$expr" "$file"
}
recreate_compose_yml() {
call_manage_tool "$PROJECT_DIR" config |&
tag_output manage
}
gen_pw() {
local len="${1:-15}"
read -r -n "$len" PW < <(LC_ALL=C tr -dc "[:alnum:]" < /dev/urandom)
echo "$PW"
}
update_config_instance_specifics() {
# Configure instance specifics in config.yml
touch "${PROJECT_DIR}/config.yml"
update_config_yml "${PROJECT_DIR}/config.yml" ".port = $PORT"
update_config_yml "${PROJECT_DIR}/config.yml" \
".stackName = \"$PROJECT_STACK_NAME\""
if [[ -n "$DOCKER_IMAGE_TAG_OPENSLIDES" ]]; then
update_config_yml "${PROJECT_DIR}/config.yml" ".defaults.tag = \"$DOCKER_IMAGE_TAG_OPENSLIDES\""
fi
update_config_yml "${PROJECT_DIR}/config.yml" \
".services.proxy.environment.ALLOWED_HOSTS = \"127.0.0.1:$PORT $PROJECT_NAME\""
}
update_config_services_db_connect_params() {
# Write DB-connection credentials to config
# for datastore
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.DATASTORE_DATABASE_NAME = \"${PROJECT_NAME}\""
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.DATASTORE_DATABASE_USER = \"${PROJECT_NAME}_user\""
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.DATASTORE_DATABASE_PASSWORD_FILE = \"/run/secrets/postgres_password\""
# for media
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.MEDIA_DATABASE_NAME = \"${PROJECT_NAME}\""
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.MEDIA_DATABASE_USER = \"${PROJECT_NAME}_user\""
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.MEDIA_DATABASE_PASSWORD_FILE = \"/run/secrets/postgres_password\""
# for vote
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.VOTE_DATABASE_NAME = \"${PROJECT_NAME}\""
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.VOTE_DATABASE_USER = \"${PROJECT_NAME}_user\""
update_config_yml "${PROJECT_DIR}/config.yml" \
".defaultEnvironment.VOTE_DATABASE_PASSWORD_FILE = \"/run/secrets/postgres_password\""
}
create_admin_secrets_file() {
echo "Generating superadmin password..."
local admin_secret="${PROJECT_DIR}/secrets/${ADMIN_SECRETS_FILE}"
rm "$admin_secret"
touch "$admin_secret"
chmod 600 "$admin_secret"
gen_pw | tr -d '\n' >> "$admin_secret"
}
query_user_account_name() {
if [[ -n "$OPT_ADD_ACCOUNT" ]]; then
echo "Create local admin account for:"
while [[ -z "$OPENSLIDES_USER_FIRSTNAME" ]] || \
[[ -z "$OPENSLIDES_USER_LASTNAME" ]]
do
read -rp "First & last name: " \
OPENSLIDES_USER_FIRSTNAME OPENSLIDES_USER_LASTNAME
read -rp "Email (optional): " OPENSLIDES_USER_EMAIL
done
fi
}
create_organization_setup_file() {
# LEGAL_NOTICE_FILE and PRIVACY_POLICY_FILE can be set in
# osinstancectl config file ($CONFIG)
local setup_file="$PROJECT_DIR/setup/organization.yml.setup"
touch "$setup_file"
yq eval -i ".[0].id = 1" "$setup_file"
[[ ! -f "$LEGAL_NOTICE_FILE" ]] ||
text="$(cat "$LEGAL_NOTICE_FILE")" \
yq eval -i ".[0].legal_notice = strenv(text)" "$setup_file"
[[ ! -f "$PRIVACY_POLICY_FILE" ]] ||
text="$(cat "$PRIVACY_POLICY_FILE")" \
yq eval -i ".[0].privacy_policy = strenv(text)" "$setup_file"
}
create_user_setup_file() {
if [[ -n "$OPT_ADD_ACCOUNT" ]]; then
local first_name
local last_name
local email # optional
local PW
echo "Generating user credentials..."
first_name=$1
last_name=$2
email=$3
PW=$(gen_pw)
local setup_file="${PROJECT_DIR}/setup/${USER_SECRETS_FILE}.setup"
touch "$setup_file"
chmod 600 "$setup_file"
cat << EOF >> "$setup_file"
---
first_name: "$first_name"
last_name: "$last_name"
username: "$first_name$last_name"
email: "$email"
default_password: "$PW"
is_active: true
organization_management_level: can_manage_organization
EOF
fi
}
create_config_template() {
if [[ -f "$CONFIG_YML_TEMPLATE" ]]; then
return 2
fi
mkdir -p "$(dirname "$CONFIG_YML_TEMPLATE")"
cat > "$CONFIG_YML_TEMPLATE" << EOF
---
filename: "$DCCONFIG_FILENAME"
host: 0.0.0.0
disablePostgres: true
disableDependsOn: true
enableLocalHTTPS: false
defaultEnvironment:
DATASTORE_DATABASE_HOST: localhost
DATASTORE_DATABASE_PORT: 5432
MEDIA_DATABASE_HOST: localhost
MEDIA_DATABASE_PORT: 5432
VOTE_DATABASE_HOST: localhost
VOTE_DATABASE_PORT: 5432
EOF
}
create_instance_dir() {
local template= config=
if [[ ! -f "$CONFIG_YML_TEMPLATE" ]]; then
warn "Configuration template $CONFIG_YML_TEMPLATE does not exist."
local REPLY
read -p "Create a mininmal template now? [Y/n] "
case "$REPLY" in
Y|y|Yes|yes|YES|"")
create_config_template
;;
*)
# Refuse to continue without a template. It would be easy to
# transparently continue with a temporary file; however, at least for
# now, encouraging the use of a central configuration file that can
# also be used with the management tool directly is the simpler and
# clearer behavior.
fatal "Cannot continue without suitable configuration template."
;;
esac
fi
[[ -z "$COMPOSE_TEMPLATE" ]] ||
template="--template=${COMPOSE_TEMPLATE}"
call_manage_tool "$PROJECT_DIR" setup |& tag_output manage ||
fatal "Error during \`"${MANAGEMENT_TOOL}" setup\`"
touch "${PROJECT_DIR}/${MARKER}"
# Restrict access to secrets b/c the management tool sets very open access
# permissions
chmod -R 600 "${PROJECT_DIR}/secrets/"
chmod 700 "${PROJECT_DIR}/secrets"
# create setup directory for payload files used by `openslides set`
mkdir "${PROJECT_DIR}/setup/"
# Note which version of the openslides tool is compatible with the instance,
# unless special string "*" is given
if [[ "$OPT_MANAGEMENT_TOOL" = '*' ]]; then
update_config_yml "${PROJECT_DIR}/config.yml" ".managementToolHash = \"$OPT_MANAGEMENT_TOOL\""
else
update_config_yml "${PROJECT_DIR}/config.yml" ".managementToolHash = \"$MANAGEMENT_TOOL_HASH\""
fi
# Due to a bug in "openslides", the db-data directory is created even if the
# stack's Postgres service that would require it is disabled.
# XXX: This is going to be fixed in the near future. For now, remain
# backwards-compatible.
if [[ -d "${PROJECT_DIR}/db-data" ]] && [[ $(value_from_config_yml "$PROJECT_DIR" '.disablePostgres') == "true" ]]
then
rmdir "${PROJECT_DIR}/db-data"
fi
}
add_to_haproxy_cfg() {
[[ -z "$OPT_LOCALONLY" ]] || return 0
cp -f "${HAPROXYCFG}" "${HAPROXYCFG}.osbak" &&
gawk -v target="${PROJECT_NAME}" -v port="${PORT}" '
BEGIN {
begin_block = "-----BEGIN AUTOMATIC OPENSLIDES CONFIG-----"
end_block = "-----END AUTOMATIC OPENSLIDES CONFIG-----"
use_server_tmpl = "\tuse-server %s if { hdr_reg(Host) -i ^%s$ }"
server_tmpl = "\tserver %s 127.0.0.1:%d weight 0 check"
}
$0 ~ begin_block { b = 1 }
$0 ~ end_block { e = 1 }
!e
b && e {
printf(use_server_tmpl "\n", target, target)
printf(server_tmpl "\n", target, port)
print
e = 0
}
' "${HAPROXYCFG}.osbak" >| "${HAPROXYCFG}" &&
systemctl reload haproxy
}
rm_from_haproxy_cfg() {
cp -f "${HAPROXYCFG}" "${HAPROXYCFG}.osbak" &&
gawk -v target="${PROJECT_NAME}" -v port="${PORT}" '
BEGIN {
begin_block = "-----BEGIN AUTOMATIC OPENSLIDES CONFIG-----"
end_block = "-----END AUTOMATIC OPENSLIDES CONFIG-----"
}
$0 ~ begin_block { b = 1 }
$0 ~ end_block { e = 1 }
b && !e && $2 == target { next }
1
' "${HAPROXYCFG}.osbak" >| "${HAPROXYCFG}" &&
systemctl reload haproxy
}
remove() {
local PROJECT_NAME="$1"
[[ -d "$PROJECT_DIR" ]] || {
fatal "$PROJECT_DIR does not exist."
}
echo "Stopping and removing containers..."