-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.sh
More file actions
executable file
·7263 lines (6416 loc) · 249 KB
/
cli.sh
File metadata and controls
executable file
·7263 lines (6416 loc) · 249 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
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
# ASCII Art Logo — only printed for interactive help, not subcommand calls
if [ $# -eq 0 ] || [ "${1:-}" = "help" ]; then
cat << "EOF"
______ ____ ______ __ __
/ ____/___ _/ / / /_ __/__ / /__ ____ ___ ___ / /________ __
/ / / __ `/ / / / / / _ \/ / _ \/ __ `__ \/ _ \/ __/ ___/ / / /
/ /___/ /_/ / / / / / / __/ / __/ / / / / / __/ /_/ / / /_/ /
\____/\__,_/_/_/ /_/ \___/_/\___/_/ /_/ /_/\___/\__/_/ \__, /
/____/
https://calltelemetry.com
EOF
fi
# Detect installation user and directory
if [ -n "${SUDO_USER:-}" ]; then
INSTALL_USER="$SUDO_USER"
INSTALL_DIR=$(eval echo "~$SUDO_USER")
else
INSTALL_USER=$(whoami)
INSTALL_DIR="$HOME"
fi
# --- Existing installation detection ---
# Prevent accidentally creating a second instance when running as root
# or from the wrong directory. Check well-known install paths for an
# existing docker-compose.yml with CallTelemetry services.
KNOWN_INSTALL_PATHS="/home/calltelemetry /opt/calltelemetry"
for check_path in $KNOWN_INSTALL_PATHS; do
if [ "$check_path" != "$INSTALL_DIR" ] && [ -f "$check_path/docker-compose.yml" ]; then
# Verify it's actually a CallTelemetry compose file (not some unrelated project)
if grep -q "calltelemetry" "$check_path/docker-compose.yml" 2>/dev/null; then
echo ""
echo " Note: Existing installation detected at $check_path"
echo " Using $check_path instead of $INSTALL_DIR"
echo ""
INSTALL_DIR="$check_path"
INSTALL_USER=$(stat -c '%U' "$check_path" 2>/dev/null || ls -ld "$check_path" | awk '{print $3}')
break
fi
fi
done
cd "$INSTALL_DIR" 2>/dev/null || true
# Directory for storing backups and other directories to be cleared
BACKUP_DIR="${INSTALL_DIR}/backups"
BACKUP_FOLDER_PATH="${INSTALL_DIR}/db_dumps"
SFTP_DIR="sftp/*"
POSTGRES_DATA_DIR="postgres-data"
# Original and backup docker-compose files
ORIGINAL_FILE="docker-compose.yml"
TEMP_FILE="temp-docker-compose.yml"
# GCS URLs for downloads (no GitHub dependency)
GCS_BASE_URL="https://storage.googleapis.com/ct_releases"
SCRIPT_URL="${GCS_BASE_URL}/cli.sh"
GCS_BUNDLE_BASE_URL="${GCS_BASE_URL}/releases"
CLI_INSTALL_PATH="${INSTALL_DIR}/cli.sh"
# Detect if running from a pipe (curl ... | sh) vs local file
if [ -f "$0" ] && [ "$0" != "sh" ] && [ "$0" != "bash" ] && [ "$0" != "-bash" ]; then
CURRENT_SCRIPT_PATH="$0"
else
CURRENT_SCRIPT_PATH="$CLI_INSTALL_PATH"
fi
# Prep script from GCS
PREP_SCRIPT_URL="${GCS_BASE_URL}/prep.sh"
# --- Self-healing bind-mount fix ---
# Docker auto-creates missing bind-mount paths as DIRECTORIES.
# If alertmanager.yml was created as a directory, fix it NOW before
# any Docker command runs. This runs on every cli.sh invocation.
if [ -d "${INSTALL_DIR}/alertmanager/alertmanager.yml" ]; then
rm -rf "${INSTALL_DIR}/alertmanager/alertmanager.yml"
fi
mkdir -p "${INSTALL_DIR}/alertmanager"
if [ ! -f "${INSTALL_DIR}/alertmanager/alertmanager.yml" ]; then
cat > "${INSTALL_DIR}/alertmanager/alertmanager.yml" << 'AMEOF'
global:
resolve_timeout: 5m
route:
receiver: 'default'
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receivers:
- name: 'default'
AMEOF
fi
if [ -d "${INSTALL_DIR}/tempo/tempo.yaml" ]; then
rm -rf "${INSTALL_DIR}/tempo/tempo.yaml"
fi
mkdir -p "${INSTALL_DIR}/tempo"
if [ ! -f "${INSTALL_DIR}/tempo/tempo.yaml" ]; then
cat > "${INSTALL_DIR}/tempo/tempo.yaml" << 'TEMPOEOF'
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 72h # Keep traces for 3 days
storage:
trace:
backend: local
local:
path: /var/tempo/blocks
wal:
path: /var/tempo/wal
metrics_generator:
registry:
external_labels:
source: tempo
storage:
path: /var/tempo/generator/wal
remote_write:
- url: http://prometheus:9090/api/v1/write
send_exemplars: true
TEMPOEOF
fi
# Repair Docker-created directories for Loki/Alloy/Tempo config bind mounts.
# Docker creates mount targets as directories when the source file doesn't exist.
# The actual config files are deployed via the release bundle (bundle-manifest.yml).
for _config_pair in "loki/loki.yaml" "alloy/config.alloy" "tempo/tempo.yaml" "otel-collector/otel-collector-config.yaml"; do
_config_path="${INSTALL_DIR}/${_config_pair}"
if [ -d "$_config_path" ]; then
rm -rf "$_config_path"
fi
done
# Remove file-provisioned Grafana dashboards that are now API-managed by BootProvisioner.
# Grafana rejects API writes to file-provisioned dashboards ("Cannot save provisioned dashboard").
# These dashboards are now generated dynamically per-org by the Elixir dashboard factory.
for _stale_dashboard in "calltelemetry-system-health.json" "alarm-overview.json" "oban-job-health.json"; do
_dash_path="${INSTALL_DIR}/grafana/dashboards/${_stale_dashboard}"
if [ -f "$_dash_path" ]; then
rm -f "$_dash_path"
fi
done
mkdir -p "${INSTALL_DIR}/prometheus"
if [ ! -f "${INSTALL_DIR}/prometheus/alert_rules.yml" ]; then
echo 'groups: []' > "${INSTALL_DIR}/prometheus/alert_rules.yml"
fi
# --- Self-healing NetworkManager fix ---
# OVA images sometimes ship with permissions=user:root:; or autoconnect=false
# in the NM connection profile, which prevents auto-connect on boot and breaks
# DNS resolution. Fix on every cli.sh invocation so networking survives reboots.
nm_heal_connections() {
command -v nmcli &>/dev/null || return 0
local changed=0
# Walk all ethernet connection files, not just the active one
for _NM_FILE in /etc/NetworkManager/system-connections/*.nmconnection; do
[ -f "$_NM_FILE" ] || continue
if grep -q 'permissions=user:root:;' "$_NM_FILE" 2>/dev/null; then
sudo sed -i 's/permissions=user:root:;//' "$_NM_FILE" 2>/dev/null
changed=1
fi
if grep -q 'autoconnect=false' "$_NM_FILE" 2>/dev/null; then
sudo sed -i 's/autoconnect=false/autoconnect=true/' "$_NM_FILE" 2>/dev/null
changed=1
fi
done
[ "$changed" = "1" ] && nmcli connection reload 2>/dev/null || true
}
nm_heal_connections
# --- Self-healing NM Docker bridge fix ---
# NetworkManager auto-creates connection profiles for Docker bridge interfaces
# (docker0, br-*, veth*) and races Docker for ownership at boot. On firewalld-
# enabled OVAs this triggers ZONE_CONFLICT and breaks container networking.
# Fix: write the conf.d unmanaged-devices rule so NM never claims these interfaces.
# Also ensure daemon.json uses the nftables firewall backend to avoid iptables/nft
# conflicts on RHEL 9 / AlmaLinux 9 OVAs.
nm_heal_docker_bridges() {
command -v nmcli &>/dev/null || return 0
local NM_DOCKER_CONF="/etc/NetworkManager/conf.d/docker-unmanaged.conf"
local changed=0
if [ ! -f "$NM_DOCKER_CONF" ]; then
sudo tee "$NM_DOCKER_CONF" > /dev/null << 'NMDEOF'
[keyfile]
unmanaged-devices=interface-name:docker*;interface-name:br-*;interface-name:veth*
NMDEOF
changed=1
fi
if [ "$changed" = "1" ]; then
sudo nmcli general reload 2>/dev/null || true
fi
# Ensure Docker uses nftables backend to avoid iptables/nftables conflicts
# with firewalld on RHEL 9 / AlmaLinux 9 OVAs.
local DAEMON_JSON="/etc/docker/daemon.json"
if [ -f "$DAEMON_JSON" ] && command -v python3 &>/dev/null; then
if ! python3 -c "import json,sys; d=json.load(open('$DAEMON_JSON')); sys.exit(0 if d.get('firewall-backend')=='nftables' and d.get('bip')=='100.64.0.1/24' else 1)" 2>/dev/null; then
python3 - "$DAEMON_JSON" << 'PYEOF'
import json, sys
path = sys.argv[1]
with open(path) as f:
d = json.load(f)
changed = False
if d.get("firewall-backend") != "nftables":
d["firewall-backend"] = "nftables"
changed = True
if d.get("bip") != "100.64.0.1/24":
d["bip"] = "100.64.0.1/24"
d["default-address-pools"] = [{"base": "100.64.0.0/14", "size": 24}]
changed = True
if changed:
with open(path, "w") as f:
json.dump(d, f, indent=2)
f.write("\n")
PYEOF
sudo systemctl reload-or-restart docker 2>/dev/null || true
fi
fi
}
nm_heal_docker_bridges
# PostgreSQL version configuration
POSTGRES_OVERRIDE_FILE="docker-compose.override.yml"
POSTGRES_DEFAULT_VERSION="17"
POSTGRES_SUPPORTED_VERSIONS="14 15 16 17 18"
POSTGRES_OVERRIDE_URL="${GCS_BASE_URL}"
# Get current PostgreSQL version from override file, or default
get_postgres_version() {
if [ -f "$POSTGRES_OVERRIDE_FILE" ]; then
# Extract version from calltelemetry/postgres:XX image line
local version=$(grep -o 'calltelemetry/postgres:[0-9]\+' "$POSTGRES_OVERRIDE_FILE" | grep -o '[0-9]\+$')
if [ -n "$version" ]; then
echo "$version"
return
fi
fi
echo "$POSTGRES_DEFAULT_VERSION"
}
# Set PostgreSQL version by downloading override file
set_postgres_version() {
local version="$1"
if ! echo "$POSTGRES_SUPPORTED_VERSIONS" | grep -qw "$version"; then
echo "Invalid PostgreSQL version: $version"
echo "Supported versions: $POSTGRES_SUPPORTED_VERSIONS"
return 1
fi
local override_url="${POSTGRES_OVERRIDE_URL}/postgres-${version}.yaml"
echo "Downloading PostgreSQL $version override..."
if wget -q "$override_url" -O "$POSTGRES_OVERRIDE_FILE"; then
echo "PostgreSQL version set to $version"
echo "Override file: $POSTGRES_OVERRIDE_FILE"
return 0
else
echo "Failed to download override file from: $override_url"
return 1
fi
}
# Get current PostgreSQL image (checks override first, then main compose)
get_current_postgres_image() {
# Check override file first
if [ -f "$POSTGRES_OVERRIDE_FILE" ]; then
local override_image=$(grep -o 'image: *"[^"]*"' "$POSTGRES_OVERRIDE_FILE" | head -1 | sed 's/image: *"\([^"]*\)"/\1/')
if [ -n "$override_image" ]; then
echo "$override_image"
return
fi
fi
# Fall back to main compose file
if [ -f "$ORIGINAL_FILE" ]; then
grep -A1 "^ db:" "$ORIGINAL_FILE" | grep "image:" | sed 's/.*image: *"\?\([^"]*\)"\?.*/\1/' | head -1
else
echo "unknown"
fi
}
# Repair missing PostgreSQL config files in an existing data directory.
# This handles upgrades from older layouts where the PG cluster existed but
# canonical config files were missing from the bind-mounted data directory.
repair_postgres_compat() {
local image="$1"
local helper=""
local script_dir
script_dir="$(cd "$(dirname "$CURRENT_SCRIPT_PATH")" && pwd)"
for candidate in \
"${INSTALL_DIR}/postgres-bitnami-convert.sh" \
"${script_dir}/postgres-bitnami-convert.sh" \
"${PWD}/postgres-bitnami-convert.sh"; do
if [ -f "$candidate" ]; then
helper="$candidate"
break
fi
done
if [ -z "$helper" ]; then
echo "[FAIL] PostgreSQL compatibility repair helper not found." >&2
echo " Expected postgres-bitnami-convert.sh in ${INSTALL_DIR} or next to cli.sh." >&2
return 1
fi
chmod +x "$helper" 2>/dev/null || true
if [ -n "$image" ] && [ "$image" != "unknown" ]; then
bash "$helper" --image "$image" --data-dir "${INSTALL_DIR}/postgres-data/data"
else
bash "$helper" --data-dir "${INSTALL_DIR}/postgres-data/data"
fi
}
ensure_timescale_preload_config() {
local compose_file="${1:-$ORIGINAL_FILE}"
local pg_conf="${INSTALL_DIR}/postgres-data/data/postgresql.conf"
local changed=false
if [ ! -f "$compose_file" ]; then
return 0
fi
# Bad release bundles stripped TimescaleDB from the compose command. The
# command line overrides postgresql.conf, so restore preload before restart
# to prevent migrations from failing on existing TimescaleDB databases.
if grep -q "shared_preload_libraries='pg_stat_statements'" "$compose_file" 2>/dev/null; then
sed -i "s/shared_preload_libraries='pg_stat_statements'/shared_preload_libraries='timescaledb,pg_stat_statements'/" "$compose_file"
changed=true
elif grep -q "shared_preload_libraries='timescaledb'" "$compose_file" 2>/dev/null; then
sed -i "s/shared_preload_libraries='timescaledb'/shared_preload_libraries='timescaledb,pg_stat_statements'/" "$compose_file"
changed=true
fi
if grep -q "shared_preload_libraries='timescaledb,pg_stat_statements'" "$compose_file" 2>/dev/null; then
if ! grep -q "timescaledb.max_background_workers" "$compose_file" 2>/dev/null; then
sed -i "/shared_preload_libraries='timescaledb,pg_stat_statements'/a\\ -c timescaledb.max_background_workers=\${TS_MAX_BACKGROUND_WORKERS:-8}\\
-c timescaledb.bgw_scheduler_restart_time=\${TS_BGW_SCHEDULER_RESTART_TIME:-60000}" "$compose_file"
changed=true
fi
fi
if [ -f "$pg_conf" ] && grep -q '^shared_preload_libraries' "$pg_conf" 2>/dev/null && \
! grep -q "^shared_preload_libraries.*timescaledb" "$pg_conf" 2>/dev/null; then
sudo sed -i -E "s/^shared_preload_libraries[[:space:]]*=.*/shared_preload_libraries = 'timescaledb,pg_stat_statements'/" "$pg_conf"
changed=true
fi
if [ "$changed" = true ]; then
echo "[OK] TimescaleDB preload settings verified"
fi
}
verify_timescale_runtime_preload() {
if ! grep -q "shared_preload_libraries='timescaledb,pg_stat_statements'" "$ORIGINAL_FILE" 2>/dev/null; then
return 0
fi
local wait_time=0
local preload=""
while [ "$wait_time" -lt 120 ]; do
preload=$($DOCKER_COMPOSE_CMD exec -T db psql -U calltelemetry -d calltelemetry_prod -tAc "SHOW shared_preload_libraries;" 2>/dev/null || true)
if echo "$preload" | grep -q "timescaledb"; then
echo "[OK] PostgreSQL runtime preload includes TimescaleDB"
return 0
fi
sleep 5
wait_time=$((wait_time + 5))
done
echo "[FAIL] PostgreSQL started without TimescaleDB in shared_preload_libraries."
echo " Current value: ${preload:-unavailable}"
echo " Refusing to continue because migrations can fail against existing TimescaleDB databases."
return 1
}
# JTAPI feature state — now driven by COMPOSE_PROFILES in .env
JTAPI_STATE_FILE=".jtapi-enabled"
ENV_FILE="${INSTALL_DIR}/.env"
# Read a key from .env (returns empty string if not found)
env_get() {
local key="$1"
if [ -f "$ENV_FILE" ]; then
grep "^${key}=" "$ENV_FILE" 2>/dev/null | head -1 | cut -d= -f2-
fi
}
# Set or update a key in .env (creates file if needed)
env_set() {
local key="$1" value="$2"
if [ ! -f "$ENV_FILE" ]; then
echo "${key}=${value}" > "$ENV_FILE"
return
fi
if grep -q "^${key}=" "$ENV_FILE" 2>/dev/null; then
sed -i "s|^${key}=.*|${key}=${value}|" "$ENV_FILE"
else
echo "${key}=${value}" >> "$ENV_FILE"
fi
}
# Set a key in .env only if it is not already set (no-clobber)
env_set_default() {
local key="$1" value="$2"
if [ -z "$(env_get "$key")" ]; then
env_set "$key" "$value"
fi
}
# Ensure baseline PG connection settings exist in .env during upgrades.
# Uses env_set_default so existing customer overrides are preserved.
# Values match the "small" profile — conservative defaults for 4-8GB appliances.
ensure_postgres_defaults() {
echo "Ensuring PostgreSQL defaults..."
env_set_default "PG_PROFILE" "small"
env_set_default "PG_MAX_CONNECTIONS" "100"
env_set_default "DB_POOL_SIZE" "15"
env_set_default "DB_CALL_CONTROL_POOL_SIZE" "15"
env_set_default "DB_BACKGROUND_POOL_SIZE" "15"
env_set_default "DB_DISCOVERY_POOL_SIZE" "15"
env_set_default "DB_OBAN_POOL_SIZE" "15"
echo "[OK] PostgreSQL defaults applied (existing values preserved)"
}
# Apply a PostgreSQL connection sizing profile (small/medium/large)
apply_postgres_profile() {
local profile="$1"
case "$profile" in
small)
env_set "PG_PROFILE" "small"
env_set "PG_MAX_CONNECTIONS" "100"
env_set "DB_POOL_SIZE" "15"
env_set "DB_CALL_CONTROL_POOL_SIZE" "15"
env_set "DB_BACKGROUND_POOL_SIZE" "15"
env_set "DB_DISCOVERY_POOL_SIZE" "15"
env_set "DB_OBAN_POOL_SIZE" "15"
;;
medium)
env_set "PG_PROFILE" "medium"
env_set "PG_MAX_CONNECTIONS" "200"
env_set "DB_POOL_SIZE" "20"
env_set "DB_CALL_CONTROL_POOL_SIZE" "20"
env_set "DB_BACKGROUND_POOL_SIZE" "20"
env_set "DB_DISCOVERY_POOL_SIZE" "20"
env_set "DB_OBAN_POOL_SIZE" "20"
;;
large)
env_set "PG_PROFILE" "large"
env_set "PG_MAX_CONNECTIONS" "300"
env_set "DB_POOL_SIZE" "25"
env_set "DB_CALL_CONTROL_POOL_SIZE" "25"
env_set "DB_BACKGROUND_POOL_SIZE" "25"
env_set "DB_DISCOVERY_POOL_SIZE" "25"
env_set "DB_OBAN_POOL_SIZE" "25"
;;
*)
echo "Usage: cli.sh postgres profile <small|medium|large|show>"
return 1
;;
esac
echo "PostgreSQL profile set to: $profile"
echo " max_connections: $(env_get PG_MAX_CONNECTIONS)"
echo " db_pool (main): $(env_get DB_POOL_SIZE)"
echo " db_pool (callctl): $(env_get DB_CALL_CONTROL_POOL_SIZE)"
echo " db_pool (background): $(env_get DB_BACKGROUND_POOL_SIZE)"
echo " db_pool (discovery): $(env_get DB_DISCOVERY_POOL_SIZE)"
echo " db_pool (oban): $(env_get DB_OBAN_POOL_SIZE)"
echo ""
echo "Restarting services to apply new profile..."
$DOCKER_COMPOSE_CMD down db 2>/dev/null
$DOCKER_COMPOSE_CMD up -d 2>/dev/null
echo "[OK] Services restarted with $profile profile"
}
# Remove a key from .env
env_remove() {
local key="$1"
[ -f "$ENV_FILE" ] && sed -i "/^${key}=/d" "$ENV_FILE"
}
# Migrate legacy .jtapi-enabled state file to .env COMPOSE_PROFILES
migrate_jtapi_state() {
if [ -f "$JTAPI_STATE_FILE" ]; then
echo "Migrating JTAPI state from .jtapi-enabled to .env COMPOSE_PROFILES..."
local profiles
profiles=$(env_get "COMPOSE_PROFILES")
if ! echo "$profiles" | grep -q "jtapi"; then
if [ -n "$profiles" ]; then
env_set "COMPOSE_PROFILES" "${profiles},jtapi"
else
env_set "COMPOSE_PROFILES" "jtapi"
fi
fi
# Set JTAPI env vars if not already present
[ -z "$(env_get JTAPI_MODE)" ] && env_set "JTAPI_MODE" "direct"
[ -z "$(env_get JTAPI_SIDECAR_ENDPOINT)" ] && env_set "JTAPI_SIDECAR_ENDPOINT" "jtapi-sidecar:50051"
[ -z "$(env_get JTAPI_SIDECAR_URL)" ] && env_set "JTAPI_SIDECAR_URL" "http://jtapi-sidecar:8080"
[ -z "$(env_get S3_ENABLED)" ] && env_set "S3_ENABLED" "true"
[ -z "$(env_get CT_MEDIA_ENDPOINT)" ] && env_set "CT_MEDIA_ENDPOINT" "ct-media:50053"
rm -f "$JTAPI_STATE_FILE"
echo "Migration complete. .jtapi-enabled removed."
fi
}
is_jtapi_enabled() {
local profiles
profiles=$(env_get "COMPOSE_PROFILES")
echo "$profiles" | grep -q "jtapi"
}
# Ensure IPv4 forwarding is enabled — Docker requires this for bridge networking.
# A kernel update or security hardening can reset this to 0, killing Docker on next boot.
ensure_ip_forward() {
local current
current=$(sysctl -n net.ipv4.ip_forward 2>/dev/null || echo "0")
if [ "$current" != "1" ]; then
echo "[cli.sh] Enabling IPv4 forwarding (was disabled — Docker requires this)"
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>&1 || true
fi
# Always ensure persistent config exists
if ! grep -q "net.ipv4.ip_forward = 1" /etc/sysctl.d/99-docker-ipforward.conf 2>/dev/null; then
echo "net.ipv4.ip_forward = 1" > /etc/sysctl.d/99-docker-ipforward.conf 2>/dev/null || true
fi
}
# Build the compose file flags — overlay no longer needed (profiles handle JTAPI)
get_compose_files() {
echo "-f docker-compose.yml"
}
# Update systemd ExecStart/ExecStop (simplified — no overlay to toggle)
fix_systemd_compose_files() {
local SERVICE_FILE="/etc/systemd/system/docker-compose-app.service"
[ -f "$SERVICE_FILE" ] || return 0
local compose_files
compose_files=$(get_compose_files)
local cmd_path
if [ "$DOCKER_COMPOSE_CMD" = "docker compose" ]; then
cmd_path="/usr/bin/docker compose"
else
cmd_path="/usr/bin/docker-compose"
fi
local new_start="ExecStart=$cmd_path $compose_files up -d"
local new_stop="ExecStop=$cmd_path $compose_files down"
if ! grep -qF "$new_start" "$SERVICE_FILE" 2>/dev/null; then
sudo cp "$SERVICE_FILE" "${SERVICE_FILE}.backup" 2>/dev/null
# Strip any leftover -f docker-compose-jtapi.yml from systemd
sudo sed -i "s|^ExecStart=.*|$new_start|" "$SERVICE_FILE"
sudo sed -i "s|^ExecStop=.*|$new_stop|" "$SERVICE_FILE"
sudo systemctl daemon-reload
echo "Updated systemd service compose files"
fi
}
# Grafana is already exposed through Caddy at /grafana, so the direct host
# port binding is redundant and can collide with other software on :3000.
# Strip that binding from appliance compose files before CLI-managed restarts.
disable_grafana_host_port_binding() {
local compose_file="${1:-$ORIGINAL_FILE}"
[ -f "$compose_file" ] || return 0
if ! grep -q 'grafana/grafana' "$compose_file" 2>/dev/null; then
return 0
fi
local tmp_file
tmp_file="$(mktemp)"
awk '
function flush_ports() {
if (!ports_captured) {
return
}
if (port_count > 0) {
print ports_header
for (i = 1; i <= port_count; i++) {
print port_lines[i]
}
}
delete port_lines
port_count = 0
ports_captured = 0
ports_header = ""
}
function is_service_boundary(line) {
return line ~ /^ [^[:space:]][^:]*:/ && line !~ /^ grafana:[[:space:]]*$/
}
BEGIN {
in_grafana = 0
ports_captured = 0
port_count = 0
}
{
if (in_grafana && is_service_boundary($0)) {
flush_ports()
in_grafana = 0
}
if ($0 ~ /^ grafana:[[:space:]]*$/) {
in_grafana = 1
print
next
}
if (in_grafana) {
if (ports_captured) {
if ($0 ~ /^ - "?3000:3000"?[[:space:]]*$/ || $0 ~ /^ - "?[$][{]GRAFANA_HOST_PORT:-3000[}]:3000"?[[:space:]]*$/) {
next
}
if ($0 ~ /^ - /) {
port_lines[++port_count] = $0
next
}
flush_ports()
}
if ($0 ~ /^ ports:[[:space:]]*$/) {
ports_captured = 1
ports_header = $0
port_count = 0
next
}
}
print
}
END {
if (in_grafana) {
flush_ports()
}
}
' "$compose_file" > "$tmp_file"
if cmp -s "$compose_file" "$tmp_file"; then
rm -f "$tmp_file"
return 0
fi
mv "$tmp_file" "$compose_file"
echo "[OK] Removed direct Grafana host port binding; use /grafana via Caddy."
}
jtapi_cmd() {
local subcmd="${1:-}"
shift 2>/dev/null || true
# Auto-migrate legacy state file on any jtapi command
migrate_jtapi_state
case "$subcmd" in
enable)
# Add jtapi to COMPOSE_PROFILES
local profiles
profiles=$(env_get "COMPOSE_PROFILES")
if ! echo "$profiles" | grep -q "jtapi"; then
if [ -n "$profiles" ]; then
env_set "COMPOSE_PROFILES" "${profiles},jtapi"
else
env_set "COMPOSE_PROFILES" "jtapi"
fi
fi
# Set JTAPI env vars
env_set "JTAPI_MODE" "direct"
env_set "JTAPI_SIDECAR_ENDPOINT" "jtapi-sidecar:50051"
env_set "JTAPI_SIDECAR_URL" "http://jtapi-sidecar:8080"
env_set "S3_ENABLED" "true"
env_set "CT_MEDIA_ENDPOINT" "ct-media:50053"
# Clean up legacy state file if present
rm -f "$JTAPI_STATE_FILE"
fix_systemd_compose_files
echo "[OK] JTAPI enabled — restarting services..."
echo ""
if ! restart_service "jtapi enable"; then
echo "[FAIL] Service restart failed. JTAPI config was saved but services may not be running."
echo " Retry with: systemctl restart docker-compose-app.service"
return 1
fi
# Force recreate web to pick up new env vars
sleep 3
$DOCKER_COMPOSE_CMD $(get_compose_files) up -d --force-recreate web 2>/dev/null
echo "Services restarted."
echo ""
echo "Next steps:"
echo " 1. Wait for sidecar to start (~90s)"
echo " 2. Upload JTAPI JAR via UI (Settings > JTAPI)"
echo " 3. Sidecar auto-restarts when JAR is received"
echo " 4. Add CUCM server via UI (Settings > JTAPI > Servers)"
echo " 5. Sidecar auto-connects when credentials appear in NATS KV"
;;
disable)
# Remove jtapi from COMPOSE_PROFILES
local profiles
profiles=$(env_get "COMPOSE_PROFILES")
local new_profiles
new_profiles=$(echo "$profiles" | sed 's/,*jtapi,*//' | sed 's/^,//' | sed 's/,$//')
env_set "COMPOSE_PROFILES" "$new_profiles"
# Clear JTAPI env vars
env_remove "JTAPI_MODE"
env_remove "JTAPI_SIDECAR_ENDPOINT"
env_remove "JTAPI_SIDECAR_URL"
env_remove "S3_ENABLED"
env_remove "CT_MEDIA_ENDPOINT"
# Clean up legacy state file if present
rm -f "$JTAPI_STATE_FILE"
fix_systemd_compose_files
echo "[OK] JTAPI disabled — restarting services..."
if ! restart_service "jtapi disable"; then
echo "[FAIL] Service restart failed. JTAPI config was saved but services may not be running."
echo " Retry with: systemctl restart docker-compose-app.service"
return 1
fi
echo "JTAPI services removed."
;;
status)
if is_jtapi_enabled; then
echo "JTAPI: enabled"
$DOCKER_COMPOSE_CMD $(get_compose_files) ps jtapi-sidecar ct-media seaweedfs 2>/dev/null || true
else
echo "JTAPI: disabled"
fi
;;
troubleshoot)
echo "=== JTAPI Troubleshooting ==="
echo ""
# --- 1. Feature State ---
echo "--- Feature State ---"
if is_jtapi_enabled; then
echo "✓ JTAPI enabled (COMPOSE_PROFILES includes jtapi)"
else
echo "[FAIL] JTAPI disabled (COMPOSE_PROFILES does not include jtapi)"
fi
echo " COMPOSE_PROFILES=$(env_get COMPOSE_PROFILES)"
echo " Compose files: $(get_compose_files)"
echo ""
# --- 2. Container Health ---
echo "--- Container Health ---"
export DEFAULT_IPV4="${DEFAULT_IPV4:-}"
for svc in jtapi-jar-init jtapi-sidecar ct-media seaweedfs; do
local cid
cid=$($DOCKER_COMPOSE_CMD $(get_compose_files) ps -q "$svc" 2>/dev/null)
if [ -z "$cid" ]; then
# Init container may not show in ps after completion — check all containers
cid=$(docker ps -a --filter "name=${svc}" --format '{{.ID}}' 2>/dev/null | head -1)
fi
if [ -z "$cid" ]; then
if [ "$svc" = "jtapi-jar-init" ]; then
echo "[WARN] $svc: not found (may have been cleaned up after successful run)"
else
echo "[FAIL] $svc: not found (not deployed or not in compose files)"
fi
else
local cstate
cstate=$(docker inspect --format='{{.State.Status}}' "$cid" 2>/dev/null || echo "unknown")
local exit_code
exit_code=$(docker inspect --format='{{.State.ExitCode}}' "$cid" 2>/dev/null || echo "N/A")
if [ "$svc" = "jtapi-jar-init" ]; then
# Init container is expected to exit with code 0
if [ "$cstate" = "exited" ] && [ "$exit_code" = "0" ]; then
echo "✓ $svc: completed successfully (exit 0)"
elif [ "$cstate" = "exited" ]; then
echo "[FAIL] $svc: failed (exit $exit_code)"
else
echo "[WARN] $svc: $cstate"
fi
elif [ "$cstate" = "running" ]; then
echo "✓ $svc: running"
else
echo "[FAIL] $svc: $cstate (exit $exit_code)"
fi
fi
done
# Show restart counts
echo ""
echo " Container restart counts:"
for svc in jtapi-sidecar ct-media seaweedfs; do
local restart_count
restart_count=$(docker inspect --format='{{.RestartCount}}' "$($DOCKER_COMPOSE_CMD $(get_compose_files) ps -q "$svc" 2>/dev/null)" 2>/dev/null || echo "N/A")
echo " $svc: $restart_count restarts"
done
echo ""
# --- 3. NATS Connectivity ---
echo "--- NATS Connectivity ---"
# Check NATS is accepting connections via health endpoint
local nats_health
nats_health=$($DOCKER_COMPOSE_CMD $(get_compose_files) exec -T nats wget -q -O- http://127.0.0.1:8222/healthz 2>&1)
if echo "$nats_health" | grep -qi "ok\|status"; then
echo "✓ NATS server is healthy"
else
# Fallback: check container health status (pgrep not available in nats:2.11 image)
local nats_status
nats_status=$($DOCKER_COMPOSE_CMD $(get_compose_files) ps nats --format '{{.Status}}' 2>/dev/null || echo "unknown")
echo " NATS: $nats_status"
fi
echo ""
# Use nats-box for KV/ObjectStore checks (nats CLI not in server image)
local CT_NETWORK
CT_NETWORK=$($DOCKER_COMPOSE_CMD $(get_compose_files) ps --format '{{.Networks}}' nats 2>/dev/null | head -1 | cut -d',' -f1)
if [ -z "$CT_NETWORK" ]; then
CT_NETWORK="calltelemetry_ct"
fi
echo " NATS KV buckets:"
docker run --rm --network "$CT_NETWORK" natsio/nats-box:0.14.5 nats -s nats://nats:4222 kv ls 2>&1 | sed 's/^/ /' || echo " [FAIL] Could not list KV buckets"
echo ""
echo " NATS ObjectStore (jtapi-jars-1):"
local objstore_result
objstore_result=$(docker run --rm --network "$CT_NETWORK" natsio/nats-box:0.14.5 nats -s nats://nats:4222 object ls jtapi-jars-1 2>&1)
if echo "$objstore_result" | grep -q "jtapi.jar"; then
echo " ✓ jtapi.jar found in NATS ObjectStore"
elif echo "$objstore_result" | grep -qi "not found\|no such\|error"; then
echo " [WARN] jtapi-jars-1 bucket: $objstore_result"
else
echo " $objstore_result" | sed 's/^/ /'
fi
echo ""
echo "--- NATS ObjectStore Buckets ---"
docker run --rm --network "$CT_NETWORK" natsio/nats-box:0.14.5 \
sh -c 'nats -s nats://nats:4222 object ls 2>/dev/null' 2>/dev/null | sed 's/^/ /' || echo " Failed to list ObjectStore buckets"
echo ""
echo "--- jtapi-jars-1 bucket contents ---"
docker run --rm --network "$CT_NETWORK" natsio/nats-box:0.14.5 \
sh -c 'nats -s nats://nats:4222 object ls jtapi-jars-1 2>/dev/null' 2>/dev/null | sed 's/^/ /' || echo " Bucket jtapi-jars-1 not found or empty"
echo ""
# --- 4. JAR Status ---
echo "--- JAR Status ---"
local jar_vol_check
jar_vol_check=$(docker run --rm -v calltelemetry_jtapi-jars:/jars alpine ls -la /jars/jtapi.jar 2>&1)
if echo "$jar_vol_check" | grep -q "jtapi.jar"; then
echo "✓ JAR found in Docker volume"
echo " $jar_vol_check"
else
echo "[FAIL] JAR not found in Docker volume"
echo " $jar_vol_check"
fi
echo ""
echo " NATS ObjectStore JAR info:"
docker run --rm --network "$CT_NETWORK" natsio/nats-box:0.14.5 nats -s nats://nats:4222 object info jtapi-jars-1 jtapi.jar 2>&1 | sed 's/^/ /' || echo " [FAIL] Could not query NATS ObjectStore"
echo ""
# --- 5. Sidecar Health ---
echo "--- Sidecar Health ---"
local sidecar_health
sidecar_health=$($DOCKER_COMPOSE_CMD $(get_compose_files) exec -T jtapi-sidecar wget -q -O- http://127.0.0.1:8080/actuator/health 2>&1 || echo "Sidecar not responding")
if echo "$sidecar_health" | grep -qi '"status":"UP"\|"status":"up"'; then
echo "✓ Sidecar health: $sidecar_health"
else
echo "[WARN] Sidecar health: $sidecar_health"
fi
echo ""
echo " Last 20 lines of sidecar logs:"
$DOCKER_COMPOSE_CMD $(get_compose_files) logs --tail=20 jtapi-sidecar 2>&1 | sed 's/^/ /'
echo ""
# --- 6. SeaweedFS Health ---
echo "--- SeaweedFS Health ---"
local seaweedfs_health
seaweedfs_health=$($DOCKER_COMPOSE_CMD $(get_compose_files) exec -T seaweedfs curl -sf http://127.0.0.1:9333/cluster/healthz 2>&1)
if [ $? -eq 0 ]; then
echo "✓ SeaweedFS is healthy"
else
echo "[FAIL] SeaweedFS health check failed: $seaweedfs_health"
fi
echo ""
echo " SeaweedFS buckets:"
$DOCKER_COMPOSE_CMD $(get_compose_files) exec -T seaweedfs curl -sf http://localhost:9333/cluster/healthz 2>&1 | sed 's/^/ /' || echo " [WARN] Could not check SeaweedFS cluster status"
echo ""
# --- 7. ct-media Health ---
echo "--- ct-media Health ---"
local media_state
media_state=$($DOCKER_COMPOSE_CMD $(get_compose_files) ps --format '{{.State}}' ct-media 2>/dev/null || echo "not found")
if [ "$media_state" = "running" ]; then
echo "✓ ct-media is running"
else
echo "[FAIL] ct-media state: ${media_state:-not found}"
fi
echo ""
echo " Last 10 lines of ct-media logs:"
$DOCKER_COMPOSE_CMD $(get_compose_files) logs --tail=10 ct-media 2>&1 | sed 's/^/ /'
echo ""
# --- 8. Web Service JTAPI Config ---
echo "--- Web Service JTAPI Config ---"
echo " Environment variables:"
$DOCKER_COMPOSE_CMD $(get_compose_files) exec -T web env 2>/dev/null | grep -E 'JTAPI|S3_|CT_MEDIA|NATS_URL' | sort | sed 's/^/ /' || echo " [FAIL] Could not read web container env"
echo ""
# --- 9. CallManager CTI Credentials Check ---
echo "--- CallManager CTI Credentials ---"
local release_bin
release_bin=$(get_release_binary)
$DOCKER_COMPOSE_CMD $(get_compose_files) exec -T web "$release_bin" rpc '
alias Cdrcisco.Repo
alias Cdrcisco.JTAPI.Servers
import Ecto.Query
servers = Repo.all(from s in Cdrcisco.JTAPI.Server, preload: [:callmanager])
if servers == [] do
IO.puts("No JTAPI servers configured")
else
Enum.each(servers, fn server ->
cm = server.callmanager
IO.puts("JTAPI Server: #{server.name || server.hostname}")
IO.puts(" CallManager: #{if cm, do: cm.name || cm.hostname, else: "NOT LINKED"}")
IO.puts(" CTI Username: #{if cm && cm.cti_username && cm.cti_username != "", do: cm.cti_username, else: "NOT SET"}")
IO.puts(" CTI Password: #{if cm && cm.cti_password, do: "****", else: "NOT SET"}")
IO.puts(" Status: #{server.status || "unknown"}")
end)
end
' 2>&1 | sed 's/^/ /' || echo " [FAIL] Could not query JTAPI server configuration (web container may not be running)"
echo ""
# --- 10. JTAPI Runtime Diagnostics (from web logs) ---
echo ""
echo "=== JTAPI Runtime Diagnostics (from web logs) ==="
echo ""
# Check for NatsSupervisor startup messages
echo "--- NATS Supervisor Startup ---"
local nats_sup_logs
nats_sup_logs=$($DOCKER_COMPOSE_CMD $(get_compose_files) logs web --tail=200 2>/dev/null | grep -i "NatsSupervisor\|jtapi_gnat\|JtapiGreeting" | tail -5)
if [ -n "$nats_sup_logs" ]; then
echo "$nats_sup_logs"
else
echo " No JTAPI NATS supervisor messages found in recent logs"
fi
# Check for ObjectStore / JarManager errors
echo ""
echo "--- JAR Manager / ObjectStore Errors ---"
local jar_logs
jar_logs=$($DOCKER_COMPOSE_CMD $(get_compose_files) logs web --tail=500 2>/dev/null | grep -i "JarManager\|ObjectStore\|object_store\|jtapi.*jar\|bucket" | tail -10)
if [ -n "$jar_logs" ]; then
echo "$jar_logs"
else
echo " No JAR/ObjectStore errors found in recent logs"
fi
# Check for gRPC client errors
echo ""
echo "--- gRPC Client Status ---"
local grpc_logs
grpc_logs=$($DOCKER_COMPOSE_CMD $(get_compose_files) logs web --tail=200 2>/dev/null | grep -i "DirectGrpcClient\|grpc.*connect\|GRPC.*error\|sidecar.*endpoint" | tail -5)
if [ -n "$grpc_logs" ]; then
echo "$grpc_logs"
else
echo " No gRPC client messages found in recent logs"
fi
# --- 11. JTAPI Health API Response ---
echo ""
echo "=== JTAPI Health API Response ==="
echo ""
# Detect Docker Compose network name (reuse CT_NETWORK if already set)
if [ -z "${CT_NETWORK:-}" ]; then
CT_NETWORK=$(docker network ls --format '{{.Name}}' 2>/dev/null | grep '_ct$' | head -1)
if [ -z "$CT_NETWORK" ]; then
CT_NETWORK="${COMPOSE_PROJECT_NAME:-$(basename "$(pwd)")}_ct"
fi