Repository navigation
Expand file tree
/
Copy pathmanage.sh
More file actions
executable file
·1864 lines (1652 loc) · 61.3 KB
/
Copy pathmanage.sh
File metadata and controls
executable file
·1864 lines (1652 loc) · 61.3 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
# CoreScope — Setup & Management Helper
# Usage: ./manage.sh [command]
#
# All container management goes through docker compose.
# Container config lives in docker-compose.yml — this script is just a wrapper.
#
# Idempotent: safe to cancel and re-run at any point.
# Each step checks what's already done and skips it.
set -e
IMAGE_NAME="corescope"
STATE_FILE=".setup-state"
STAGING_CONTAINER="corescope-staging-go"
# Source .env for port/path overrides (same file docker compose reads)
# Strip \r (Windows line endings) to avoid "$'\r': command not found"
if [ -f .env ]; then
set -a
while IFS='=' read -r key value || [ -n "$key" ]; do
key=$(printf '%s' "$key" | sed 's/\r$//' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
[[ "$key" =~ ^#.*$ || -z "$key" ]] && continue
value=$(printf '%s' "$value" | sed 's/\r$//' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
value="${value/#\~/$HOME}"
export "$key=$value"
done < .env
set +a
fi
# Auto-fix CRLF in .env if detected
if [ -f .env ] && grep -qP '\r' .env 2>/dev/null; then
warn ".env has Windows line endings (CRLF) — fixing automatically..."
sed -i 's/\r$//' .env
log ".env converted to Unix line endings."
fi
# Resolved paths for prod/staging data (must match docker-compose.yml)
PROD_DATA="${PROD_DATA_DIR:-$HOME/meshcore-data}"
STAGING_DATA="${STAGING_DATA_DIR:-$HOME/meshcore-staging-data}"
STAGING_COMPOSE_FILE="docker-compose.staging.yml"
# Build metadata — exported so docker compose build picks them up via args
export APP_VERSION=$(git describe --tags --match "v*" 2>/dev/null || echo "unknown")
export GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
export BUILD_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# Docker Compose — detect v2 plugin vs v1 standalone
if docker compose version &>/dev/null 2>&1; then
DC="docker compose"
elif command -v docker-compose &>/dev/null; then
DC="docker-compose"
else
echo "ERROR: Neither '$DC' nor 'docker-compose' found." >&2
exit 1
fi
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
log() { printf '%b\n' "${GREEN}✓${NC} $1"; }
warn() { printf '%b\n' "${YELLOW}⚠${NC} $1"; }
err() { printf '%b\n' "${RED}✗${NC} $1"; }
info() { printf '%b\n' "${CYAN}→${NC} $1"; }
step() { printf '%b\n' "\n${BOLD}[$1/$TOTAL_STEPS] $2${NC}"; }
# DISABLE_MOSQUITTO (#441): the bundled mosquitto is opt-in. Prints "true"
# (bundled broker off), "false" (on) or "invalid". Trimmed and
# case-insensitive: true/1/yes/on and false/0/no/off; unset or empty is the
# default, true. docker/entrypoint-go.sh and the ingestor's
# ResolveBrokerMode read it with the same table
# (test-fixtures/disable-mosquitto-cases.json), and an invalid value falls
# back to the default in all three.
parse_disable_mosquitto() {
local v
v=$(printf '%s' "${1:-}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]')
case "$v" in
true|1|yes|on|"") echo true ;;
false|0|no|off) echo false ;;
*) echo invalid ;;
esac
}
# True unless DISABLE_MOSQUITTO (or the value given) is a recognised false.
mosquitto_disabled() {
[ "$(parse_disable_mosquitto "${1-${DISABLE_MOSQUITTO:-}}")" != "false" ]
}
dc_prod() {
if mosquitto_disabled; then
$DC -f docker-compose.no-mosquitto.yml "$@"
else
$DC "$@"
fi
}
dc_staging() {
if mosquitto_disabled; then
$DC -f docker-compose.staging.no-mosquitto.yml -p corescope-staging "$@"
else
$DC -f "$STAGING_COMPOSE_FILE" -p corescope-staging "$@"
fi
}
confirm() {
read -p " $1 [y/N] " -n 1 -r
echo
[[ $REPLY =~ ^[Yy]$ ]]
}
# State tracking — marks completed steps so re-runs skip them
mark_done() { echo "$1" >> "$STATE_FILE"; }
is_done() { [ -f "$STATE_FILE" ] && grep -qx "$1" "$STATE_FILE" 2>/dev/null; }
# ─── Helpers ──────────────────────────────────────────────────────────────
resolve_domain_ipv4() {
local domain="$1"
local resolved_ip=""
if command -v dig >/dev/null 2>&1; then
resolved_ip=$(dig +short "$domain" 2>/dev/null | grep -E '^[0-9]+\.' | head -1)
fi
if [ -z "$resolved_ip" ] && command -v host >/dev/null 2>&1; then
resolved_ip=$(host "$domain" 2>/dev/null | awk '/has address/ {print $4; exit}')
fi
if [ -z "$resolved_ip" ] && command -v nslookup >/dev/null 2>&1; then
resolved_ip=$(nslookup "$domain" 2>/dev/null | awk '/^Address: / {print $2}' | grep -E '^[0-9]+\.' | head -1)
fi
if [ -z "$resolved_ip" ] && command -v getent >/dev/null 2>&1; then
resolved_ip=$(getent hosts "$domain" 2>/dev/null | awk '{print $1}' | grep -E '^[0-9]+\.' | head -1)
fi
echo "$resolved_ip"
}
has_dns_resolution_tool() {
command -v dig >/dev/null 2>&1 || \
command -v host >/dev/null 2>&1 || \
command -v nslookup >/dev/null 2>&1 || \
command -v getent >/dev/null 2>&1
}
PORT_CHECK_METHOD=""
resolve_port_check_method() {
if [ -n "$PORT_CHECK_METHOD" ]; then
return 0
fi
if command -v ss &>/dev/null; then
PORT_CHECK_METHOD="ss"
elif command -v lsof &>/dev/null; then
PORT_CHECK_METHOD="lsof"
elif command -v netstat &>/dev/null; then
PORT_CHECK_METHOD="netstat"
elif command -v nc &>/dev/null; then
PORT_CHECK_METHOD="nc"
else
PORT_CHECK_METHOD="none"
fi
}
# Returns 0 when in use, 1 when free, 2 when unavailable
is_port_in_use() {
local port="$1"
resolve_port_check_method
case "$PORT_CHECK_METHOD" in
ss)
ss -tlnp 2>/dev/null | grep -E "[[:space:]]LISTEN[[:space:]].*[:.]${port}([[:space:]]|$)" >/dev/null
return $?
;;
lsof)
lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1
return $?
;;
netstat)
netstat -tlnp 2>/dev/null | grep -E "[[:space:]]${port}[[:space:]]" >/dev/null
if [ $? -eq 0 ]; then
return 0
fi
netstat -tlnp 2>/dev/null | grep -E "[:.]${port}[[:space:]]" >/dev/null
return $?
;;
nc)
local bind_pid=""
( nc -l 127.0.0.1 "$port" >/dev/null 2>&1 ) &
bind_pid=$!
sleep 0.2
if kill -0 "$bind_pid" 2>/dev/null; then
kill "$bind_pid" 2>/dev/null || true
wait "$bind_pid" 2>/dev/null || true
return 1
fi
wait "$bind_pid" 2>/dev/null || true
return 0
;;
*)
return 2
;;
esac
}
port_in_use_details() {
local port="$1"
resolve_port_check_method
case "$PORT_CHECK_METHOD" in
ss)
ss -tlnp 2>/dev/null | grep -E "[[:space:]]LISTEN[[:space:]].*[:.]${port}([[:space:]]|$)" | head -1
;;
lsof)
lsof -nP -iTCP:"$port" -sTCP:LISTEN 2>/dev/null | sed -n '2p'
;;
netstat)
netstat -tlnp 2>/dev/null | grep -E "[:.]${port}[[:space:]]" | head -1
;;
*)
echo ""
;;
esac
}
find_next_available_port() {
local start="$1"
local candidate=$((start + 1))
while [ "$candidate" -le 65535 ]; do
is_port_in_use "$candidate"
local rc=$?
if [ "$rc" -eq 0 ]; then
candidate=$((candidate + 1))
continue
fi
if [ "$rc" -eq 1 ]; then
echo "$candidate"
return 0
fi
break
done
echo ""
return 1
}
is_valid_port() {
local value="$1"
[[ "$value" =~ ^[0-9]+$ ]] && [ "$value" -ge 1 ] && [ "$value" -le 65535 ]
}
show_env_port_summary() {
local http_port="$1"
local https_port="$2"
local mqtt_port="$3"
local data_dir="$4"
local disable_mosquitto="$5"
echo ""
echo " Current .env values:"
echo " PROD_HTTP_PORT=${http_port}"
echo " PROD_HTTPS_PORT=${https_port}"
echo " PROD_MQTT_PORT=${mqtt_port}"
echo " DISABLE_MOSQUITTO=${disable_mosquitto}"
echo " PROD_DATA_DIR=${data_dir}"
echo ""
}
get_env_value() {
local key="$1"
local env_file="${2:-.env}"
if [ ! -f "$env_file" ]; then
echo ""
return 1
fi
sed -n "s/^[[:space:]]*${key}[[:space:]]*=[[:space:]]*//p" "$env_file" | head -1
}
write_env_managed_values() {
local http_port="$1"
local https_port="$2"
local mqtt_port="$3"
local data_dir="$4"
local disable_mosquitto="$5"
local env_file=".env"
local tmp_file=".env.tmp.$$"
if [ ! -f "$env_file" ]; then
cp .env.example "$env_file"
fi
local seen_http=0
local seen_https=0
local seen_mqtt=0
local seen_data=0
local seen_disable_mosquitto=0
: > "$tmp_file"
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
PROD_HTTP_PORT=*)
echo "PROD_HTTP_PORT=${http_port}" >> "$tmp_file"
seen_http=1
;;
PROD_HTTPS_PORT=*)
echo "PROD_HTTPS_PORT=${https_port}" >> "$tmp_file"
seen_https=1
;;
PROD_MQTT_PORT=*)
echo "PROD_MQTT_PORT=${mqtt_port}" >> "$tmp_file"
seen_mqtt=1
;;
PROD_DATA_DIR=*)
echo "PROD_DATA_DIR=${data_dir}" >> "$tmp_file"
seen_data=1
;;
DISABLE_MOSQUITTO=*)
echo "DISABLE_MOSQUITTO=${disable_mosquitto}" >> "$tmp_file"
seen_disable_mosquitto=1
;;
*)
echo "$line" >> "$tmp_file"
;;
esac
done < "$env_file"
[ "$seen_http" -eq 1 ] || echo "PROD_HTTP_PORT=${http_port}" >> "$tmp_file"
[ "$seen_https" -eq 1 ] || echo "PROD_HTTPS_PORT=${https_port}" >> "$tmp_file"
[ "$seen_mqtt" -eq 1 ] || echo "PROD_MQTT_PORT=${mqtt_port}" >> "$tmp_file"
[ "$seen_data" -eq 1 ] || echo "PROD_DATA_DIR=${data_dir}" >> "$tmp_file"
[ "$seen_disable_mosquitto" -eq 1 ] || echo "DISABLE_MOSQUITTO=${disable_mosquitto}" >> "$tmp_file"
mv "$tmp_file" "$env_file"
}
prompt_for_port() {
local label="$1"
local current="$2"
local prompt_default="$3"
while true; do
if [ -n "$prompt_default" ] && [ "$prompt_default" != "$current" ]; then
read -p " ${label} port [${prompt_default}] (current ${current}): " selected
selected=${selected:-$prompt_default}
else
read -p " ${label} port [${current}]: " selected
selected=${selected:-$current}
fi
if ! is_valid_port "$selected"; then
warn "Invalid port '${selected}'. Enter a value between 1 and 65535."
continue
fi
is_port_in_use "$selected"
local rc=$?
if [ "$rc" -eq 0 ]; then
warn "Port ${selected} is in use."
local details
details=$(port_in_use_details "$selected")
[ -n "$details" ] && echo " ${details}"
if confirm "Use ${selected} anyway? (start will fail if still occupied)"; then
echo "$selected"
return 0
fi
continue
fi
if [ "$rc" -eq 2 ]; then
warn "Port detection unavailable on this host. Proceeding with chosen value."
fi
echo "$selected"
return 0
done
}
preflight_validate_prod_ports() {
local http_port="${PROD_HTTP_PORT:-80}"
local https_port="${PROD_HTTPS_PORT:-443}"
local mqtt_port=""
if ! mosquitto_disabled; then
mqtt_port="${PROD_MQTT_PORT:-1883}"
fi
local failed=0
info "Preflight: validating configured ports are free..."
local ports_to_check=("$http_port" "$https_port")
[ -n "$mqtt_port" ] && ports_to_check+=("$mqtt_port")
for port in "${ports_to_check[@]}"; do
if is_port_in_use "$port"; then
err "Port ${port} is in use."
local details
details=$(port_in_use_details "$port")
[ -n "$details" ] && echo " ${details}"
failed=1
fi
done
if [ "$failed" -eq 1 ]; then
echo ""
echo " Remediation:"
echo " • Stop the process using the conflicting port(s)"
echo " • Or run ./manage.sh setup and re-negotiate ports"
echo " • Then re-run this command"
return 1
fi
log "Preflight port validation passed."
return 0
}
# Check config.json for placeholder values
check_config_placeholders() {
local cfg="${1:-$PROD_DATA/config.json}"
if [ -f "$cfg" ]; then
if grep -qE 'your-username|your-password|your-secret|example\.com|changeme' "$cfg" 2>/dev/null; then
warn "config.json contains placeholder values."
warn "Edit ${cfg} and replace placeholder values before deploying."
fi
fi
}
# ─── Broker Preflight (#372) ──────────────────────────────────────────────
#
# DISABLE_MOSQUITTO=true turns the bundled mosquitto off but configures no
# replacement. With no mqttSources the ingestor falls back to its built-in
# mqtt://localhost:1883 — the bundled broker's own address, where nothing is
# then listening — so ingest stops while the deploy still looks healthy.
# These helpers say so before a setup, start, update, restore or promote.
#
# They are advisory: this script never refuses a command over a broker
# diagnostic, because the right answer differs per host. Only the explicit
# `./manage.sh broker-check` exits non-zero, so an operator (or a runbook)
# can gate on it deliberately.
# Remove credentials from anything about to be printed: the user-info of a
# URL, a bare user:pass@ pair, and any query string. Reads stdin, writes
# stdout. Used for broker URLs out of config.json and for log lines echoed
# straight out of `docker logs`, which may come from an ingestor of any
# version.
mask_broker_text() {
sed -E \
-e 's#[^[:space:]:/@]+:[^[:space:]:/@]+@#****@#g' \
-e 's#([a-zA-Z][a-zA-Z0-9+.-]*://)[^/@[:space:]]+@#\1****@#g' \
-e 's#(://[^[:space:]]*)\?[^[:space:]]*#\1#g'
}
# True when the bundled mosquitto will run. manage.sh, the entrypoint and
# the ingestor all read DISABLE_MOSQUITTO with parse_disable_mosquitto's
# table (#441), so the mode reported here is the mode the container is in
# whichever compose file is used.
bundled_broker_enabled() {
! mosquitto_disabled
}
# Host part of a broker URL, lowercased, with scheme, user-info, port and
# path removed.
broker_host() {
local u="${1#*://}"
u="${u##*@}"
u="${u%%/*}"
u="${u%%\?*}"
case "$u" in
\[*\]*) u="${u%%]*}"; u="${u#[}" ;;
*:*) u="${u%:*}" ;;
esac
printf '%s' "$u" | tr 'A-Z' 'a-z'
}
# True for a host only reachable from inside the same network namespace.
is_loopback_host() {
case "${1:-}" in
localhost|ip6-localhost|ip6-loopback|::1|127.*|*.localhost) return 0 ;;
esac
return 1
}
# The "broker" string values in whatever JSON text arrives on stdin.
broker_urls() {
grep -oE '"broker"[[:space:]]*:[[:space:]]*"[^"]*"' 2>/dev/null \
| sed -E 's/^"broker"[[:space:]]*:[[:space:]]*"//; s/"$//'
}
# The text of the mqttSources array in a config.json, or nothing when the key
# is absent. Bracket-matched and string-aware, so a "]" inside a topic
# pattern cannot end the array early.
mqtt_sources_region() {
awk '
{ buf = buf $0 "\n" }
END {
k = index(buf, "\"mqttSources\"")
if (k == 0) exit
n = length(buf)
i = k + length("\"mqttSources\"")
while (i <= n && substr(buf, i, 1) != "[") {
c = substr(buf, i, 1)
if (c != ":" && c != " " && c != "\t" && c != "\n" && c != "\r") exit
i++
}
if (i > n) exit
depth = 0; instr = 0; esc = 0
for (; i <= n; i++) {
c = substr(buf, i, 1)
out = out c
if (esc) { esc = 0; continue }
if (instr) {
if (c == "\\") esc = 1
else if (c == "\"") instr = 0
continue
}
if (c == "\"") { instr = 1; continue }
if (c == "[") depth++
else if (c == "]") { depth--; if (depth == 0) break }
}
printf "%s", out
}
' "$1"
}
# The broker URLs the ingestor will use, one per line, in the ingestor's own
# precedence (see LoadConfig):
#
# MQTT_BROKER > config.json mqttSources[] > legacy config.json mqtt.broker
#
# The legacy mqtt.broker block is promoted to a source ONLY when mqttSources
# yields none, so it must not be counted next to mqttSources — the ingestor
# never connects to it in that case, and a loopback legacy block would
# otherwise produce a "cannot connect" warning about a source nothing uses.
broker_sources() {
local cfg="${1:-$PROD_DATA/config.json}"
if [ -n "${MQTT_BROKER:-}" ]; then
printf '%s\n' "$MQTT_BROKER"
return 0
fi
[ -f "$cfg" ] || return 0
local region urls
region=$(mqtt_sources_region "$cfg")
if [ -n "$region" ]; then
urls=$(printf '%s' "$region" | broker_urls)
if [ -n "$urls" ]; then
printf '%s\n' "$urls"
return 0
fi
fi
# No mqttSources, or an empty one: LoadConfig promotes mqtt.broker.
broker_urls < "$cfg"
}
# Report the broker arrangement. Returns 1 when something means no packets
# can be ingested, 0 otherwise. Every broker URL printed is masked.
broker_check_report() {
local cfg="${1:-$PROD_DATA/config.json}"
local errors=0
local raw="${DISABLE_MOSQUITTO:-}"
local parsed setting
parsed=$(parse_disable_mosquitto "$raw")
case "$parsed" in
invalid)
warn "DISABLE_MOSQUITTO='${raw}' is not a recognised value (true/1/yes/on or false/0/no/off)."
echo " The default applies, so the bundled broker will NOT start. Set it to \"false\""
echo " to run the bundled broker, or to \"true\" to silence this warning."
setting="DISABLE_MOSQUITTO=${raw}, not recognised, default true"
;;
*)
if [ -z "$raw" ]; then
setting="DISABLE_MOSQUITTO unset, default true"
else
setting="DISABLE_MOSQUITTO=${raw}, read as ${parsed}"
fi
;;
esac
if bundled_broker_enabled; then
log "Broker mode: bundled mosquitto (${setting})."
return 0
fi
info "Broker mode: external (${setting}) — the bundled broker will not start."
local sources
sources=$(broker_sources "$cfg")
if [ -z "$sources" ]; then
err "No external MQTT source is configured, so nothing will be ingested."
echo " The bundled broker is off (it is opt-in), but the ingestor then"
echo " falls back to its built-in mqtt://localhost:1883 — the bundled broker's own"
echo " address — where nothing is listening."
echo ""
echo " Remediation:"
echo " • Add mqttSources to ${cfg} pointing at your broker"
echo " • Or set MQTT_BROKER=mqtt://your-broker:1883 in .env"
echo " • Or set DISABLE_MOSQUITTO=false to use the bundled broker"
return 1
fi
local total=0 loopback=0 line host
while IFS= read -r line; do
[ -n "$line" ] || continue
total=$((total + 1))
host=$(broker_host "$line")
if [ -z "$host" ]; then
err "MQTT source $(printf '%s' "$line" | mask_broker_text) has no host."
errors=1
continue
fi
if is_loopback_host "$host"; then
loopback=$((loopback + 1))
warn "MQTT source $(printf '%s' "$line" | mask_broker_text) points at loopback."
else
log "MQTT source $(printf '%s' "$line" | mask_broker_text)"
fi
done <<EOSRC
$sources
EOSRC
if [ "$total" -gt 0 ] && [ "$loopback" -eq "$total" ]; then
err "All ${total} configured MQTT source(s) point at loopback, where the disabled"
echo " bundled broker used to listen. Nothing will be ingested."
echo ""
echo " Remediation:"
echo " • Point the source(s) at the external broker's address"
echo " • Or set DISABLE_MOSQUITTO=false to use the bundled broker"
errors=1
elif [ "$loopback" -gt 0 ]; then
warn "${loopback} of ${total} MQTT source(s) cannot connect; the rest still ingest."
fi
[ "$errors" -eq 0 ]
}
cmd_broker_check() {
echo ""
info "Checking the MQTT broker arrangement..."
if broker_check_report "${1:-$PROD_DATA/config.json}"; then
log "Broker check passed."
return 0
fi
echo ""
err "Broker check failed. See the remediation above."
echo " Set MQTT_SOURCE_STRICT=true to make the ingestor refuse to start in this state."
exit 1
}
# Verify the running container is actually healthy
verify_health() {
local container="corescope-prod"
local use_https=false
# Check if Caddyfile has a real domain (not :80)
if [ -f caddy-config/Caddyfile ]; then
local caddyfile_domain
caddyfile_domain=$(grep -v '^#' caddy-config/Caddyfile 2>/dev/null | head -1 | tr -d ' {')
if [ "$caddyfile_domain" != ":80" ] && [ -n "$caddyfile_domain" ]; then
use_https=true
fi
fi
# Wait for /api/stats response (Go backend loads packets into memory — may take 60s+)
info "Waiting for server to respond..."
local healthy=false
for i in $(seq 1 45); do
if docker exec "$container" wget -qO- http://localhost:3000/api/stats &>/dev/null; then
healthy=true
break
fi
sleep 2
done
if ! $healthy; then
err "Server did not respond after 90 seconds."
warn "Check logs: ./manage.sh logs"
return 1
fi
log "Server is responding."
# Check for MQTT errors in recent logs
local mqtt_errors
mqtt_errors=$(docker logs "$container" --tail 50 2>&1 | grep -i 'mqtt.*error\|mqtt.*fail\|ECONNREFUSED.*1883' || true)
if [ -n "$mqtt_errors" ]; then
warn "MQTT errors detected in logs:"
# Masked: a log line from an ingestor of any version can quote a broker
# URL with its user-info, and this output ends up in bug reports.
echo "$mqtt_errors" | head -5 | mask_broker_text | sed 's/^/ /'
fi
# If HTTPS domain configured, try to verify externally
if $use_https; then
info "Checking HTTPS for ${caddyfile_domain}..."
if command -v curl &>/dev/null; then
if curl -sf --connect-timeout 5 "https://${caddyfile_domain}/api/stats" &>/dev/null; then
log "HTTPS is working: https://${caddyfile_domain}"
else
warn "HTTPS not reachable yet for ${caddyfile_domain}"
warn "It may take a minute for Caddy to provision the certificate."
fi
fi
fi
return 0
}
# ─── Setup Wizard ─────────────────────────────────────────────────────────
TOTAL_STEPS=6
cmd_setup() {
echo ""
echo "═══════════════════════════════════════"
echo " CoreScope Setup"
echo "═══════════════════════════════════════"
echo ""
if [ -f "$STATE_FILE" ]; then
info "Resuming previous setup. Delete ${STATE_FILE} to start over."
echo ""
fi
# ── Step 1: Check Docker ──
step 1 "Checking Docker"
if ! command -v docker &> /dev/null; then
err "Docker is not installed."
echo ""
echo " Install it:"
echo " curl -fsSL https://get.docker.com | sh"
echo " sudo usermod -aG docker \$USER"
echo ""
echo " Then log out, log back in, and run ./manage.sh setup again."
exit 1
fi
# Check if user can actually run Docker
if ! docker info &> /dev/null; then
err "Docker is installed but your user can't run it."
echo ""
echo " Fix: sudo usermod -aG docker \$USER"
echo " Then log out, log back in, and try again."
exit 1
fi
log "Docker $(docker --version | grep -oP 'version \K[^ ,]+')"
log "Compose: $DC"
# Default to latest release tag (instead of staying on master)
if ! is_done "version_pin"; then
git fetch origin --tags --force 2>/dev/null || true
local latest_tag
latest_tag=$(git tag -l 'v*' --sort=-v:refname | head -1)
if [ -n "$latest_tag" ]; then
local current_ref
current_ref=$(git describe --tags --exact-match 2>/dev/null || echo "")
if [ "$current_ref" != "$latest_tag" ]; then
info "Pinning to latest release: ${latest_tag}"
git checkout "$latest_tag" 2>/dev/null
else
log "Already on latest release: ${latest_tag}"
fi
fi
mark_done "version_pin"
fi
mark_done "docker"
# ── Step 2: Config ──
step 2 "Configuration"
if [ -f "$PROD_DATA/config.json" ]; then
log "config.json found in data directory."
# Sanity check the JSON
if ! python3 -c "import json; json.load(open('$PROD_DATA/config.json'))" 2>/dev/null && \
! node -e "JSON.parse(require('fs').readFileSync('$PROD_DATA/config.json'))" 2>/dev/null; then
err "config.json has invalid JSON. Fix it and re-run setup."
exit 1
fi
log "config.json is valid JSON."
check_config_placeholders "$PROD_DATA/config.json"
elif [ -f config.json ]; then
# Legacy: config in repo root — move it to data dir
info "Found config.json in repo root — moving to data directory..."
mkdir -p "$PROD_DATA"
cp config.json "$PROD_DATA/config.json"
log "Config moved to ${PROD_DATA}/config.json"
check_config_placeholders "$PROD_DATA/config.json"
else
info "Creating config.json in data directory from example..."
mkdir -p "$PROD_DATA"
cp config.example.json "$PROD_DATA/config.json"
# Generate a random API key
if command -v openssl &> /dev/null; then
API_KEY=$(openssl rand -hex 16)
else
API_KEY=$(head -c 32 /dev/urandom | xxd -p | head -c 32)
fi
# Replace the placeholder API key
if command -v sed &> /dev/null; then
sed -i "s/your-secret-api-key-here/${API_KEY}/" "$PROD_DATA/config.json"
fi
log "Created config.json with random API key."
check_config_placeholders "$PROD_DATA/config.json"
echo ""
echo " Config saved to: ${PROD_DATA}/config.json"
echo " Edit with: nano ${PROD_DATA}/config.json"
echo ""
fi
mark_done "config"
# ── Step 3: Ports & Networking ──
step 3 "Ports & Networking"
local default_http=80
local default_https=443
local default_mqtt=1883
local selected_http="$default_http"
local selected_https="$default_https"
local selected_mqtt="$default_mqtt"
local selected_disable_mosquitto="${DISABLE_MOSQUITTO:-true}"
local selected_data_dir="${PROD_DATA_DIR:-$HOME/meshcore-data}"
local env_http=""
local env_https=""
local env_mqtt=""
local env_disable_mosquitto=""
local env_data_dir=""
if [ -f .env ]; then
env_http=$(get_env_value "PROD_HTTP_PORT" ".env")
env_https=$(get_env_value "PROD_HTTPS_PORT" ".env")
env_mqtt=$(get_env_value "PROD_MQTT_PORT" ".env")
env_disable_mosquitto=$(get_env_value "DISABLE_MOSQUITTO" ".env")
env_data_dir=$(get_env_value "PROD_DATA_DIR" ".env")
env_data_dir="${env_data_dir/#\~/$HOME}"
[ -n "$env_data_dir" ] && selected_data_dir="$env_data_dir"
[ -n "$env_disable_mosquitto" ] && selected_disable_mosquitto="$env_disable_mosquitto"
show_env_port_summary "${env_http:-<unset>}" "${env_https:-<unset>}" "${env_mqtt:-<unset>}" "${env_data_dir:-<unset>}" "${env_disable_mosquitto:-<unset>}"
else
info ".env not found. It will be created from .env.example."
fi
local has_current_ports=false
if mosquitto_disabled "$selected_disable_mosquitto"; then
if is_valid_port "$env_http" && is_valid_port "$env_https"; then
has_current_ports=true
fi
elif is_valid_port "$env_http" && is_valid_port "$env_https" && is_valid_port "$env_mqtt"; then
has_current_ports=true
fi
local renegotiate=true
if [ -f .env ] && $has_current_ports; then
if confirm "Keep current ports from .env?"; then
renegotiate=false
selected_http="$env_http"
selected_https="$env_https"
if is_valid_port "$env_mqtt"; then
selected_mqtt="$env_mqtt"
fi
log "Keeping current ports from .env."
fi
fi
if $renegotiate; then
resolve_port_check_method
if [ "$PORT_CHECK_METHOD" = "none" ]; then
warn "No supported port detection tool found (ss/lsof/netstat/nc)."
warn "You'll still be prompted, but conflicts cannot be detected now."
else
info "Detecting listeners using ${PORT_CHECK_METHOD}..."
fi
local suggested_http="$default_http"
local suggested_https="$default_https"
local suggested_mqtt="$default_mqtt"
if is_port_in_use "$default_http"; then
warn "Port ${default_http} is in use."
local details_http
details_http=$(port_in_use_details "$default_http")
[ -n "$details_http" ] && echo " ${details_http}"
suggested_http=$(find_next_available_port "$default_http")
[ -n "$suggested_http" ] && info "Suggested HTTP port: ${suggested_http}"
fi
if is_port_in_use "$default_https"; then
warn "Port ${default_https} is in use."
local details_https
details_https=$(port_in_use_details "$default_https")
[ -n "$details_https" ] && echo " ${details_https}"
suggested_https=$(find_next_available_port "$default_https")
[ -n "$suggested_https" ] && info "Suggested HTTPS port: ${suggested_https}"
fi
selected_http=$(prompt_for_port "HTTP" "$default_http" "$suggested_http")
selected_https=$(prompt_for_port "HTTPS" "$default_https" "$suggested_https")
# The bundled broker is opt-in (#441), so Enter keeps it off.
if confirm "Use built-in MQTT broker?"; then
selected_disable_mosquitto="false"
if is_port_in_use "$default_mqtt"; then
warn "Port ${default_mqtt} is in use."
local details_mqtt
details_mqtt=$(port_in_use_details "$default_mqtt")
[ -n "$details_mqtt" ] && echo " ${details_mqtt}"
suggested_mqtt=$(find_next_available_port "$default_mqtt")
[ -n "$suggested_mqtt" ] && info "Suggested MQTT port: ${suggested_mqtt}"
fi
selected_mqtt=$(prompt_for_port "MQTT" "$default_mqtt" "$suggested_mqtt")
else
selected_disable_mosquitto="true"
log "Internal MQTT broker disabled. Point mqttSources in config.json at your broker."
fi
fi
if [ -f caddy-config/Caddyfile ]; then
EXISTING_DOMAIN=$(grep -v '^#' caddy-config/Caddyfile 2>/dev/null | head -1 | tr -d ' {')
if [ "$EXISTING_DOMAIN" = ":80" ] || [ "$EXISTING_DOMAIN" = ":${selected_http}" ]; then
log "Caddyfile exists (HTTP only, no HTTPS)."
else
log "Caddyfile exists for ${EXISTING_DOMAIN}"
fi
else
mkdir -p caddy-config
echo ""
echo " How should the analyzer be accessed?"
echo ""
echo " 1) Direct with built-in HTTPS — Caddy auto-provisions a TLS cert"
echo " (requires ports 80 + 443 open, and a domain pointed at this server)"
echo ""
echo " 2) Behind my own reverse proxy — HTTP only"
echo " (for Cloudflare Tunnel, nginx, Traefik, etc.)"
echo ""
read -p " Choose [1/2]: " -n 1 -r
echo ""
case $REPLY in
1)
read -p " Enter your domain (e.g., analyzer.example.com): " DOMAIN
if [ -z "$DOMAIN" ]; then
err "No domain entered. Re-run setup to try again."
exit 1
fi
echo "${DOMAIN} {
reverse_proxy localhost:3000
}" > caddy-config/Caddyfile
log "Caddyfile created for ${DOMAIN}"
# Validate DNS
info "Checking DNS..."
RESOLVED_IP=$(resolve_domain_ipv4 "$DOMAIN")
MY_IP=$(curl -s -4 ifconfig.me 2>/dev/null || curl -s -4 icanhazip.com 2>/dev/null || echo "unknown")
if [ -z "$RESOLVED_IP" ]; then
if has_dns_resolution_tool; then
warn "${DOMAIN} doesn't resolve yet."
warn "Create an A record pointing to ${MY_IP}"
warn "HTTPS won't work until DNS propagates (1-60 min)."
else
warn "DNS tool not found; skipping domain resolution check."
fi
echo ""
if ! confirm "Continue anyway?"; then
echo " Run ./manage.sh setup again when DNS is ready."
exit 0
fi
elif [ "$RESOLVED_IP" = "$MY_IP" ]; then
log "DNS resolves correctly: ${DOMAIN} → ${MY_IP}"
else
warn "${DOMAIN} resolves to ${RESOLVED_IP} but this server is ${MY_IP}"
warn "HTTPS provisioning will fail if the domain doesn't point here."
if ! confirm "Continue anyway?"; then
echo " Fix DNS and run ./manage.sh setup again."
exit 0
fi
fi
;;
2)
echo ":${selected_http} {
reverse_proxy localhost:3000
}" > caddy-config/Caddyfile
log "Caddyfile created (HTTP only on port ${selected_http})."
echo " Point your reverse proxy or tunnel to this server's port ${selected_http}."
;;
*)
warn "Invalid choice. Defaulting to HTTP only."
echo ":${selected_http} {
reverse_proxy localhost:3000
}" > caddy-config/Caddyfile
;;
esac
fi
write_env_managed_values "$selected_http" "$selected_https" "$selected_mqtt" "$selected_data_dir" "$selected_disable_mosquitto"
log "Saved negotiated ports to .env"
show_env_port_summary "$selected_http" "$selected_https" "$selected_mqtt" "$selected_data_dir" "$selected_disable_mosquitto"
echo " Resolved port mapping:"
echo " UI HTTP: ${selected_http}"