Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·890 lines (813 loc) · 38.7 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·890 lines (813 loc) · 38.7 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
#!/usr/bin/env bash
################################################################################
# CyberController Container Watchdog - Installation Script
#
# Installs the watchdog Docker container that monitors all containers on the
# host and fires alerts (Slack, SMTP, SNMP) on crashes, OOM-kills,
# unhealthy states, and restart loops.
#
# Usage:
# bash install.sh
################################################################################
# Errors are handled explicitly with exit 1 throughout this script
# ── Detect color support ──────────────────────────────────────────────────────
if [ "${FORCE_COLOR:-0}" = "1" ] || ([ -t 1 ] && command -v tput &>/dev/null && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]); then
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
else
RED='' GREEN='' YELLOW='' BLUE='' NC=''
fi
# ── Constants ─────────────────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_DIR="$SCRIPT_DIR" # package is already extracted to the install directory
IMAGE_ARCHIVE="${SCRIPT_DIR}/watchdog.tar"
CONTAINER_NAME="docker-container-watchdog"
VERSION_FILE="${SCRIPT_DIR}/VERSION"
# Single source of truth for the release: the packaged VERSION file. The image
# is pinned to it so an upgrade can never silently keep serving the previous
# build that also happens to be tagged :latest.
VERSION="$(tr -d '[:space:]' < "$VERSION_FILE" 2>/dev/null || true)"
if [ -z "$VERSION" ]; then
echo "ERROR: VERSION file missing or empty: ${VERSION_FILE}" >&2
echo " Re-extract the installation package and try again." >&2
exit 1
fi
IMAGE_NAME="watchdog:${VERSION}"
IMAGE_LATEST="watchdog:latest" # convenience tag only — never the deployed reference
RUN_UID="1000" # non-root runtime user baked in by this installer
RUN_GID="1000"
DC="" # compose command — set automatically in check_prerequisites
################################################################################
# Helper Functions
################################################################################
print_header() {
echo -e "${BLUE}╔═══════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║${NC} ${GREEN}CyberController Container Watchdog - Installation${NC} ${BLUE}║${NC}"
echo -e "${BLUE}║${NC} Version: ${VERSION} ${BLUE}║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════════════════════════╝${NC}"
echo ""
}
print_success() { echo -e "${GREEN}✓${NC} $1"; }
print_error() { echo -e "${RED}✗${NC} $1" >&2; }
print_warning() { echo -e "${YELLOW}⚠${NC} $1"; }
print_info() { echo -e "${BLUE}ℹ${NC} $1"; }
print_section() {
echo ""
echo -e "${BLUE}═══${NC} $1"
echo ""
}
################################################################################
# Privileged File Helpers
#
# Config files left behind by an older, root-run installation are commonly
# 600 root:root. A docker-group user re-running this installer must still be
# able to migrate them, so every write goes through these helpers: attempt
# unprivileged first, escalate to sudo, and fail loudly instead of leaving a
# half-migrated file behind.
################################################################################
# Prints the privilege prefix to use ("sudo" or nothing); non-zero if elevation
# is needed but unavailable.
_priv_prefix() {
[ "$EUID" -eq 0 ] && return 0
command -v sudo &>/dev/null && { printf 'sudo'; return 0; }
return 1
}
# Usage: _run_priv <cmd...> — run unprivileged, retry with sudo on failure.
_run_priv() {
"$@" 2>/dev/null && return 0
local priv
priv=$(_priv_prefix) || return 1
[ -z "$priv" ] && return 1 # already root: retrying changes nothing
$priv "$@"
}
# Usage: _publish_file SRC DST MODE [OWNER:GROUP]
# Replaces DST with SRC's contents, then applies MODE/OWNER.
_publish_file() {
local src="$1" dst="$2" mode="$3" owner="${4:-}"
if ! _run_priv cp "$src" "$dst"; then
print_error "Failed to write ${dst}"
echo ""
echo " The file is not writable by $(id -un) and sudo is unavailable."
echo " Re-run this installer as root."
return 1
fi
if [ -n "$owner" ] && ! _run_priv chown "$owner" "$dst"; then
print_error "Failed to set ownership ${owner} on ${dst}"
return 1
fi
if ! _run_priv chmod "$mode" "$dst"; then
print_error "Failed to set permissions ${mode} on ${dst}"
return 1
fi
return 0
}
# Usage: _read_file_priv FILE — cat a file, escalating if it is not readable.
_read_file_priv() {
local file="$1"
[ -e "$file" ] || return 1 # never prompt for sudo just to miss a file
[ -r "$file" ] && { cat "$file"; return $?; }
local priv
priv=$(_priv_prefix) || return 1
[ -z "$priv" ] && return 1
$priv cat "$file"
}
# Usage: update_env_vars FILE KEY=VALUE...
# Upserts each KEY=VALUE, preserving the file's existing owner, then verifies
# every value really landed on disk before returning success.
update_env_vars() {
local file="$1"; shift
local tmp tmp2 kv key rc=0
tmp=$(mktemp) || { print_error "Could not create a temporary file"; return 1; }
tmp2=$(mktemp) || { rm -f "$tmp"; print_error "Could not create a temporary file"; return 1; }
chmod 600 "$tmp" "$tmp2"
if ! _read_file_priv "$file" > "$tmp"; then
print_error "Cannot read ${file} — not readable by $(id -un) and sudo is unavailable"
rm -f "$tmp" "$tmp2"
return 1
fi
for kv in "$@"; do
key="${kv%%=*}"
if grep -q -e "^${key}=" "$tmp"; then
# index() instead of sed: values may contain / & \ and other
# characters that would be interpreted in a substitution.
awk -v key="$key" -v line="$kv" \
'index($0, key "=") == 1 { print line; next } { print }' "$tmp" > "$tmp2" \
&& cat "$tmp2" > "$tmp"
else
printf '%s\n' "$kv" >> "$tmp"
fi
done
if ! _publish_file "$tmp" "$file" 600; then
rm -f "$tmp" "$tmp2"
return 1
fi
# Read back: a successful cp is not proof the values are present, and
# silently continuing here is what left upgrades running as root before.
if ! _read_file_priv "$file" > "$tmp2"; then
print_error "Cannot verify ${file} after writing it"
rm -f "$tmp" "$tmp2"
return 1
fi
for kv in "$@"; do
if ! grep -qxF "$kv" "$tmp2"; then
print_error "Failed to save ${kv%%=*} in ${file}"
rc=1
fi
done
rm -f "$tmp" "$tmp2"
if [ "$rc" -ne 0 ]; then
echo ""
echo " Add the following lines to ${file} manually and re-run:"
printf ' %s\n' "$@"
return 1
fi
# Compose reads .env as the user running it — that is this user, right now.
if [ ! -r "$file" ]; then
print_warning "${file} is not readable by $(id -un) — handing it to this user"
if ! _run_priv chown "$(id -u):$(id -g)" "$file"; then
print_error "Could not make ${file} readable by $(id -un) — docker compose will fail"
return 1
fi
fi
return 0
}
# watchdog-config.yaml is bind-mounted read-only into a container running as
# RUN_UID:RUN_GID. Keep it root-owned and group-readable: the runtime can read
# it, but UID 1000 on the host cannot rewrite probe commands and indirectly
# control Docker exec operations.
harden_config_permissions() {
local file="$1"
[ -f "$file" ] || return 0
if ! _run_priv chown "0:${RUN_GID}" "$file"; then
print_error "Failed to set ownership of ${file} to root:GID ${RUN_GID}"
echo ""
echo " Fix manually:"
echo " sudo chown root:${RUN_GID} ${file} && sudo chmod 640 ${file}"
return 1
fi
if ! _run_priv chmod 640 "$file"; then
print_error "Failed to set permissions 640 on ${file}"
return 1
fi
print_success "Config secured as root:${RUN_GID}, mode 640 (runtime read-only)"
return 0
}
################################################################################
# Pre-flight Checks
################################################################################
check_prerequisites() {
print_section "Checking Prerequisites"
# Docker
if ! command -v docker &>/dev/null; then
print_error "Docker is not installed or not in PATH"
echo ""
echo " Please install Docker before running this script."
echo " See: https://docs.docker.com/get-docker/"
exit 1
fi
print_success "Docker is installed: $(docker --version)"
if ! docker info &>/dev/null; then
print_error "Docker daemon is not running"
echo ""
echo " Start it with: sudo systemctl start docker"
exit 1
fi
print_success "Docker daemon is running"
# Docker Compose — accept v2 plugin (docker compose) or v1 standalone (docker-compose)
if docker compose version &>/dev/null 2>&1; then
DC="docker compose"
print_success "Docker Compose is available (v2 plugin): $(docker compose version --short)"
elif command -v docker-compose &>/dev/null; then
DC="docker-compose"
print_success "Docker Compose is available (v1 standalone): $(docker-compose --version)"
else
print_error "Docker Compose not found"
echo ""
echo " Install the v2 plugin: sudo apt-get install docker-compose-plugin"
echo " Install v1 standalone: sudo apt-get install docker-compose"
echo " Or see: https://docs.docker.com/compose/install/"
exit 1
fi
# Root / sudo warning
if [ "$EUID" -ne 0 ]; then
print_warning "Not running as root — you may be prompted for sudo on some steps"
fi
}
################################################################################
# Log Directory
################################################################################
setup_log_directory() {
print_section "Setting Up Log Directory"
LOG_DIR="${INSTALL_DIR}/watchdog"
if [ ! -d "$LOG_DIR" ]; then
mkdir -p "$LOG_DIR"
print_success "Created log directory: ${LOG_DIR}"
else
print_info "Log directory already exists: ${LOG_DIR}"
fi
# This installer hardens the container to run as UID/GID 1000 (see
# detect_docker_gid below) instead of the compose file's root default, so
# it must own the dir and any pre-existing files up front.
if ! _run_priv chown -R "${RUN_UID}:${RUN_GID}" "$LOG_DIR"; then
print_error "Failed to set ownership of ${LOG_DIR} to UID ${RUN_UID}:GID ${RUN_GID}"
echo ""
echo " Fix ownership manually before starting:"
echo " sudo chown -R ${RUN_UID}:${RUN_GID} ${LOG_DIR} && sudo chmod 750 ${LOG_DIR}"
exit 1
fi
if ! _run_priv chmod 750 "$LOG_DIR"; then
print_error "Failed to set permissions on ${LOG_DIR}"
exit 1
fi
print_info "Logs will be written to: ${LOG_DIR}/watchdog.log"
}
################################################################################
# Docker Socket Group Detection
################################################################################
detect_docker_gid() {
# GID that owns /var/run/docker.sock — the non-root container joins this
# group (via group_add in docker-compose.yaml) to read the socket.
# No silent fallback: a wrong guessed GID breaks socket access at container
# start with a confusing error, so treat detection failure as fatal here.
if [ ! -S /var/run/docker.sock ]; then
print_error "/var/run/docker.sock not found — cannot determine its group GID"
return 1
fi
local gid
gid=$(stat -c '%g' /var/run/docker.sock 2>/dev/null || stat -f '%g' /var/run/docker.sock 2>/dev/null)
if [ -z "$gid" ]; then
print_error "Could not determine the GID that owns /var/run/docker.sock"
return 1
fi
echo "$gid"
}
################################################################################
# Docker Image
################################################################################
# Confirm that an image carries the release version, not just an arbitrary tag.
verify_release_image() {
local reported_version
docker image inspect "$IMAGE_NAME" >/dev/null 2>&1 || return 1
reported_version=$(docker image inspect "$IMAGE_NAME" \
--format '{{index .Config.Labels "org.opencontainers.image.version"}}' 2>/dev/null) || return 1
if [ "$reported_version" != "$VERSION" ]; then
print_warning "$IMAGE_NAME has version label '$reported_version', expected '$VERSION'"
return 1
fi
}
# Verify the image archive checksum shipped in every release package.
load_release_archive() {
local archive="$1" sums="$2" expected actual loaded
if [ ! -r "$archive" ] || [ ! -r "$sums" ] || ! command -v sha256sum >/dev/null 2>&1; then
print_error "Release image or checksum is missing; image not loaded"
return 1
fi
expected=$(awk '$2 == "watchdog.tar" || $2 == "*watchdog.tar" {print $1}' "$sums" | tail -n1)
if ! [[ "$expected" =~ ^[a-fA-F0-9]{64}$ ]]; then
print_error "SHA256SUMS has no valid digest for watchdog.tar"
return 1
fi
actual=$(sha256sum "$archive" | awk '{print $1}') || return 1
if [ "$actual" != "$expected" ]; then
print_error "Archive checksum mismatch; image not loaded"
return 1
fi
print_success "Archive checksum verified"
if ! loaded=$(docker load -i "$archive" 2>&1); then
print_error "Docker could not load the image"
printf '%s\n' "$loaded"
return 1
fi
if ! printf '%s\n' "$loaded" | grep -Fxq "Loaded image: $IMAGE_NAME"; then
print_error "Archive does not contain the expected tag $IMAGE_NAME"
return 1
fi
if ! verify_release_image; then
print_error "Loaded image does not match release version $VERSION"
return 1
fi
print_success "Loaded and verified $IMAGE_NAME"
}
# One release bundle contains its version-labelled Docker image.
# A missing or invalid archive aborts before changing application configuration.
load_docker_image() {
print_section "Load Release Image"
if [ ! -f "$IMAGE_ARCHIVE" ] || [ ! -f "$INSTALL_DIR/SHA256SUMS" ]; then
print_error "Incomplete release package: watchdog.tar and SHA256SUMS are required"
echo " Download and extract the complete container-alert-v$VERSION.tar.gz package."
echo " No running containers have been changed."
return 1
fi
load_release_archive "$IMAGE_ARCHIVE" "$INSTALL_DIR/SHA256SUMS"
}
################################################################################
# Prompt Utilities
################################################################################
_prompt() {
# Usage: val=$(_prompt "Label" "default")
local label="$1" default="$2" val
[ -n "$default" ] \
&& printf " %s [%s]: " "$label" "$default" >&2 \
|| printf " %s: " "$label" >&2
IFS= read -r val
printf "%s" "${val:-$default}"
}
_prompt_secret() {
# Usage: val=$(_prompt_secret "Label") — input is hidden
local label="$1" val
printf " %s: " "$label" >&2
IFS= read -rs val
printf "\n" >&2
printf "%s" "$val"
}
_prompt_yn() {
# Usage: result=$(_prompt_yn "Label" "yes|no") → prints "true" or "false"
local label="$1" default="${2:-yes}" val
printf " %s [%s]: " "$label" "$default" >&2
IFS= read -r val
val="${val:-$default}"
[[ "$val" =~ ^[Yy] ]] && printf "true" || printf "false"
}
_in_array() {
# Usage: _in_array "needle" "${array[@]}"
local needle="$1"; shift
for item in "$@"; do [ "$item" = "$needle" ] && return 0; done
return 1
}
################################################################################
# Interactive Configuration Wizard
################################################################################
configure_all() {
print_section "Configuration Wizard"
ENV_FILE="${INSTALL_DIR}/.env"
CONFIG_FILE="${INSTALL_DIR}/watchdog-config.yaml"
# Keeping a half-present configuration breaks the deployment: a missing .env
# aborts compose on env_file, and a missing watchdog-config.yaml makes Docker
# create a directory at the bind-mount path. Only offer to keep when both exist.
if { [ -f "$ENV_FILE" ] || [ -f "$CONFIG_FILE" ]; } && \
{ [ ! -f "$ENV_FILE" ] || [ ! -f "$CONFIG_FILE" ]; }; then
local missing=""
[ -f "$ENV_FILE" ] || missing+=" .env"
[ -f "$CONFIG_FILE" ] || missing+=" watchdog-config.yaml"
print_warning "Incomplete configuration — missing:${missing}"
print_error "Restore the missing configuration file from backup, then rerun."
print_info "Existing configuration was not changed."
return 1
# Offer to reconfigure if files already exist
elif [ -f "$ENV_FILE" ] && [ -f "$CONFIG_FILE" ]; then
print_info "Existing configuration detected: .env watchdog-config.yaml"
printf " Reconfigure from scratch? [y/N]: "
local RECONFIG
IFS= read -r RECONFIG
if [[ ! "$RECONFIG" =~ ^[Yy]$ ]]; then
print_info "Keeping existing configuration"
# Upgrade path: installs from before non-root hardening existed
# predate these vars, which would silently fall back to the
# compose file's root default instead of the intended hardening.
# WATCHDOG_VERSION is refreshed on every run so the container is
# redeployed on the release that was just loaded.
if [ -f "$ENV_FILE" ]; then
local CURRENT_GID MIGRATED_GID
CURRENT_GID=$(_read_file_priv "$ENV_FILE" | grep -E '^DOCKER_GID=' | tail -n1 | cut -d= -f2 | tr -d '[:space:]')
MIGRATED_GID=$(detect_docker_gid) || exit 1
if [[ "$CURRENT_GID" =~ ^[0-9]+$ ]] && [ "$CURRENT_GID" != "$MIGRATED_GID" ]; then
print_warning "Docker socket GID changed: ${CURRENT_GID} -> ${MIGRATED_GID}; updating .env"
elif ! [[ "$CURRENT_GID" =~ ^[0-9]+$ ]]; then
print_warning "Existing .env predates non-root hardening — adding detected Docker socket GID"
fi
if ! update_env_vars "$ENV_FILE" \
"WATCHDOG_UID=${RUN_UID}" \
"WATCHDOG_GID=${RUN_GID}" \
"DOCKER_GID=${MIGRATED_GID}" \
"WATCHDOG_VERSION=${VERSION}"; then
exit 1
fi
print_success "Set WATCHDOG_UID=${RUN_UID}, WATCHDOG_GID=${RUN_GID}, DOCKER_GID=${MIGRATED_GID}, WATCHDOG_VERSION=${VERSION} in ${ENV_FILE}"
fi
# An older install may have left the config root-owned and 600,
# which the non-root container cannot read.
harden_config_permissions "$CONFIG_FILE" || exit 1
return 0
fi
# Preserve both existing files before explicitly requested reconfiguration.
local backup_dir
backup_dir="$INSTALL_DIR/backup/$(date -u +%Y%m%dT%H%M%SZ)"
if ! _run_priv mkdir -p "$backup_dir" || ! _run_priv chmod 700 "$backup_dir" || \
! _run_priv cp -p "$ENV_FILE" "$backup_dir/.env" || \
! _run_priv cp -p "$CONFIG_FILE" "$backup_dir/watchdog-config.yaml"; then
print_error "Could not back up existing configuration; aborting reconfiguration"
return 1
fi
print_success "Existing configuration backed up in: $backup_dir"
echo ""
fi
# ── Channel selection ─────────────────────────────────────────────────────
echo -e " ${BLUE}Select alert channels${NC} (space-separated numbers, at least one required):"
echo ""
echo " 1) Slack"
echo " 2) SMTP (email)"
echo " 3) SNMP Trap"
echo " 4) Syslog"
echo ""
local SELECTED_CHANNELS=()
while [ ${#SELECTED_CHANNELS[@]} -eq 0 ]; do
printf " Channels [1]: "
local RAW_SELECTION
IFS= read -r RAW_SELECTION
RAW_SELECTION="${RAW_SELECTION:-1}"
for num in $RAW_SELECTION; do
case "$num" in
1) SELECTED_CHANNELS+=("slack") ;;
2) SELECTED_CHANNELS+=("smtp") ;;
3) SELECTED_CHANNELS+=("snmp_trap") ;;
4) SELECTED_CHANNELS+=("syslog") ;;
*) print_warning " Unknown choice: $num — ignored" ;;
esac
done
[ ${#SELECTED_CHANNELS[@]} -eq 0 ] && print_error "Select at least one channel"
done
local CHANNELS_LABEL
CHANNELS_LABEL=$(printf ", %s" "${SELECTED_CHANNELS[@]}")
print_success "Channels: ${CHANNELS_LABEL:2}"
echo ""
# ── Slack ─────────────────────────────────────────────────────────────────
local SLACK_WEBHOOK="" SLACK_ENABLED="false"
if _in_array "slack" "${SELECTED_CHANNELS[@]}"; then
SLACK_ENABLED="true"
print_info "Slack"
while true; do
SLACK_WEBHOOK=$(_prompt_secret "Webhook URL (https://hooks.slack.com/...)")
[[ "$SLACK_WEBHOOK" == https://hooks.slack.com/* ]] && break
print_error " Must start with https://hooks.slack.com/"
done
echo ""
fi
# ── SMTP ──────────────────────────────────────────────────────────────────
local SMTP_HOST="smtp.example.com" SMTP_PORT="587"
local SMTP_SENDER="sender@example.com" SMTP_RECIPIENTS="alerts@example.com"
local SMTP_TLS="true" SMTP_AUTH="true" SMTP_USERNAME="" SMTP_PASSWORD="" SMTP_ENABLED="false"
if _in_array "smtp" "${SELECTED_CHANNELS[@]}"; then
SMTP_ENABLED="true"
print_info "SMTP (email)"
SMTP_HOST=$(_prompt "Server host" "smtp.example.com")
SMTP_PORT=$(_prompt "Port" "587")
SMTP_SENDER=$(_prompt "Sender address" "sender@example.com")
SMTP_RECIPIENTS=$(_prompt "Recipients (comma-separated)" "alerts@example.com")
SMTP_TLS=$(_prompt_yn "Use TLS?" "yes")
SMTP_AUTH=$(_prompt_yn "Server requires authentication (login)?" "yes")
if [ "$SMTP_AUTH" = "true" ]; then
SMTP_USERNAME=$(_prompt "SMTP username / login email" "")
SMTP_PASSWORD=$(_prompt_secret "SMTP password / api key value")
else
print_info " No-auth relay — skipping username/password"
fi
echo ""
fi
# ── SNMP Trap ─────────────────────────────────────────────────────────────
local SNMP_HOST="" SNMP_PORT="162" SNMP_COMMUNITY="public"
local SNMP_ENABLED="false"
local SNMP_VERSION="v2c" SNMP_V3_USER="" SNMP_V3_AUTH_PROTO="SHA"
local SNMP_V3_AUTH_KEY="" SNMP_V3_PRIV_PROTO="AES" SNMP_V3_PRIV_KEY=""
if _in_array "snmp_trap" "${SELECTED_CHANNELS[@]}"; then
SNMP_ENABLED="true"
print_info "SNMP Trap"
SNMP_HOST=$(_prompt "Receiver host / IP" "")
SNMP_PORT=$(_prompt "Receiver port" "162")
SNMP_VERSION=$(_prompt "SNMP version (v1 / v2c / v3)" "v2c")
if [ "${SNMP_VERSION,,}" = "v3" ]; then
SNMP_V3_USER=$(_prompt "USM username" "")
SNMP_V3_AUTH_PROTO=$(_prompt "Auth protocol (MD5 / SHA)" "SHA")
SNMP_V3_AUTH_KEY=$(_prompt_secret "Auth passphrase (empty = noAuthNoPriv)")
SNMP_V3_PRIV_PROTO=$(_prompt "Priv protocol (DES / AES)" "AES")
SNMP_V3_PRIV_KEY=$(_prompt_secret "Priv passphrase (empty = authNoPriv)")
else
SNMP_COMMUNITY=$(_prompt "Community string" "public")
fi
echo ""
fi
# ── Syslog ────────────────────────────────────────────────────────────────
local SYSLOG_HOST="" SYSLOG_PORT="514" SYSLOG_PROTO="udp"
local SYSLOG_FACILITY="local0" SYSLOG_ENABLED="false"
if _in_array "syslog" "${SELECTED_CHANNELS[@]}"; then
SYSLOG_ENABLED="true"
print_info "Syslog"
SYSLOG_HOST=$(_prompt "Server host / IP" "")
SYSLOG_PORT=$(_prompt "Port" "514")
SYSLOG_PROTO=$(_prompt "Protocol (udp/tcp)" "udp")
SYSLOG_FACILITY=$(_prompt "Facility" "local0")
echo ""
fi
# ── Optional HA monitoring (separate from alert delivery channels) ──────
local HA_ENABLED HA_EXPORTER_URL="http://127.0.0.1:9664/metrics"
print_info "Optional CyberController HA monitoring"
HA_ENABLED=$(_prompt_yn "Enable active-node change alerts? (configure both HA nodes)" "no")
if [ "$HA_ENABLED" = "true" ]; then
HA_EXPORTER_URL=$(_prompt "Local HA exporter URL" "$HA_EXPORTER_URL")
fi
echo ""
# ── Hostname shown in alerts ──────────────────────────────────────────────
print_info "Identity"
local HOST_DEFAULT WATCHDOG_HOST
HOST_DEFAULT=$(hostname -f 2>/dev/null || hostname 2>/dev/null || echo "")
WATCHDOG_HOST=$(_prompt "Hostname to display in alerts" "$HOST_DEFAULT")
echo ""
# ── Non-root hardening (manual `docker compose up` defaults to root instead) ──
local WATCHDOG_UID="$RUN_UID" WATCHDOG_GID="$RUN_GID" DOCKER_GID
DOCKER_GID=$(detect_docker_gid) || exit 1
print_info "Docker socket GID detected: ${DOCKER_GID} — running non-root as UID/GID ${WATCHDOG_UID}"
# ── Write .env ────────────────────────────────────────────────────────────
# Staged in a temp file so a root-owned .env from a previous install can
# still be replaced (via sudo) instead of failing on an unwritable target.
local ENV_TMP
ENV_TMP=$(mktemp) || { print_error "Could not create a temporary file"; exit 1; }
chmod 600 "$ENV_TMP"
{
printf "# .env — generated by install.sh on %s\n" "$(date '+%Y-%m-%d %H:%M:%S')"
printf "# Secrets and deployment settings; monitoring policy is in watchdog-config.yaml.\n\n"
if [ "$SLACK_ENABLED" = "true" ]; then
printf "# Slack\nSLACK_WEBHOOK_URL=%s\n\n" "$SLACK_WEBHOOK"
fi
if [ "$SMTP_ENABLED" = "true" ] && [ "$SMTP_AUTH" = "true" ]; then
printf "# SMTP\nSMTP_USERNAME=%s\nSMTP_PASSWORD=%s\n\n" "$SMTP_USERNAME" "$SMTP_PASSWORD"
fi
if [ "$SNMP_ENABLED" = "true" ] && [ "${SNMP_VERSION,,}" = "v3" ]; then
printf "# SNMP v3\nSNMP_V3_AUTH_KEY=%s\nSNMP_V3_PRIV_KEY=%s\n\n" \
"$SNMP_V3_AUTH_KEY" "$SNMP_V3_PRIV_KEY"
fi
printf "# Alert identity\nWATCHDOG_HOST=%s\n\n" "$WATCHDOG_HOST"
printf "# Non-root hardening\nWATCHDOG_UID=%s\nWATCHDOG_GID=%s\nDOCKER_GID=%s\n\n" \
"$WATCHDOG_UID" "$WATCHDOG_GID" "$DOCKER_GID"
printf "# Deployed release — docker-compose.yaml pins watchdog:\${WATCHDOG_VERSION}\n"
printf "WATCHDOG_VERSION=%s\n\n" "$VERSION"
} > "$ENV_TMP"
if ! _publish_file "$ENV_TMP" "$ENV_FILE" 600 "$(id -u):$(id -g)"; then
rm -f "$ENV_TMP"
exit 1
fi
rm -f "$ENV_TMP"
print_success ".env written: ${ENV_FILE}"
# ── Build alert_channels YAML list ────────────────────────────────────────
local CHANNELS_YAML=""
for ch in "${SELECTED_CHANNELS[@]}"; do
CHANNELS_YAML+=" - ${ch}"$'\n'
done
# ── Convert comma-separated SMTP recipients to YAML list ─────────────────
local RECIPIENTS_YAML=""
IFS=',' read -ra RECIP_ARRAY <<< "$SMTP_RECIPIENTS"
for r in "${RECIP_ARRAY[@]}"; do
r=$(echo "$r" | tr -d '[:space:]')
[ -n "$r" ] && RECIPIENTS_YAML+=" - ${r}"$'\n'
done
[ -z "$RECIPIENTS_YAML" ] && RECIPIENTS_YAML=" - alerts@example.com"$'\n'
# ── Write watchdog-config.yaml ────────────────────────────────────────────
local CONFIG_TMP
CONFIG_TMP=$(mktemp) || { print_error "Could not create a temporary file"; exit 1; }
{
printf "# watchdog-config.yaml — generated by install.sh on %s\n" "$(date '+%Y-%m-%d %H:%M:%S')"
printf "# Edit values, then restart: %s -f %s/docker-compose.yaml restart\n\n" \
"$DC" "$INSTALL_DIR"
printf "alert_channels:\n%s" "$CHANNELS_YAML"
printf "\ncheck_interval_seconds: 60\n"
printf "cooldown_minutes: 5\n"
printf "restart_threshold: 5\n"
printf "restart_window_minutes: 10\n"
printf "unhealthy_cycles_threshold: 3\n"
printf "\nexcluded_containers: []\n"
printf "\nignored_container_events:\n"
printf " - label:\n"
printf " com.radware.cybercontroller.role: mariadb-ha-syntax-check\n"
printf " events:\n"
printf " - die\n"
printf "# Temporary MariaDB HA syntax-check containers should carry the label shown above.\n"
printf "# Fallback: suppress kvision_infra_mariadb AutoRemove dump helpers exiting 137\n"
printf "# only when /mnt/cli/tmp/mariadb_dump.sql.gz is mounted; primary MariaDB stays monitored.\n"
printf "\nrunbook_base_url: \"\"\n"
printf "\nlog_level: INFO\n"
printf "log_file: /var/log/watchdog/watchdog.log\n"
printf "state_file: /var/log/watchdog/state.json\n"
printf "boot_grace_seconds: 180\n"
printf "\n# Optional HA active-node alerts; enable on both HA nodes.\n"
printf "ha_monitor:\n"
printf " enabled: %s\n" "$HA_ENABLED"
printf " exporter_url: %s\n" "$HA_EXPORTER_URL"
printf "\nsyslog:\n"
printf " enabled: %s\n" "$SYSLOG_ENABLED"
printf " host: %s\n" "${SYSLOG_HOST:-127.0.0.1}"
printf " port: %s\n" "$SYSLOG_PORT"
printf " protocol: %s\n" "$SYSLOG_PROTO"
printf " facility: %s\n" "$SYSLOG_FACILITY"
printf "\nsmtp:\n"
printf " enabled: %s\n" "$SMTP_ENABLED"
printf " auth: %s\n" "$SMTP_AUTH"
printf " host: %s\n" "$SMTP_HOST"
printf " port: %s\n" "$SMTP_PORT"
printf " sender: %s\n" "$SMTP_SENDER"
printf " username_env: SMTP_USERNAME\n"
printf " recipients:\n%s" "$RECIPIENTS_YAML"
printf " tls: %s\n" "$SMTP_TLS"
printf " password_env: SMTP_PASSWORD\n"
printf "\nsnmp_trap:\n"
printf " enabled: %s\n" "$SNMP_ENABLED"
printf " host: %s\n" "${SNMP_HOST:-127.0.0.1}"
printf " port: %s\n" "$SNMP_PORT"
printf " version: %s\n" "${SNMP_VERSION:-v2c}"
printf " community: %s\n" "$SNMP_COMMUNITY"
if [ "${SNMP_VERSION,,}" = "v3" ]; then
printf " v3_username: %s\n" "$SNMP_V3_USER"
printf " v3_auth_protocol: %s\n" "${SNMP_V3_AUTH_PROTO:-SHA}"
printf " v3_auth_key_env: SNMP_V3_AUTH_KEY\n"
printf " v3_priv_protocol: %s\n" "${SNMP_V3_PRIV_PROTO:-AES}"
printf " v3_priv_key_env: SNMP_V3_PRIV_KEY\n"
fi
printf "\nslack:\n"
printf " enabled: %s\n" "$SLACK_ENABLED"
printf " webhook_url_env: SLACK_WEBHOOK_URL\n"
printf "\nauto_health_check:\n"
printf " enabled: true\n"
printf " paths:\n"
printf " - /-/healthy\n"
printf " - /health\n"
printf " - /healthz\n"
printf " - /api/health\n"
printf " - /metrics\n"
printf " - /\n"
printf " timeout_seconds: 2\n"
printf "\ncontainer_health_checks: {}\n"
} > "$CONFIG_TMP"
# Root-owned, runtime-group-readable. This prevents host UID 1000 from
# rewriting exec health-check commands while still allowing the non-root
# container to read the bind-mounted file.
if ! _publish_file "$CONFIG_TMP" "$CONFIG_FILE" 640 "0:${RUN_GID}"; then
rm -f "$CONFIG_TMP"
exit 1
fi
rm -f "$CONFIG_TMP"
print_success "watchdog-config.yaml written: ${CONFIG_FILE}"
}
################################################################################
# Start Watchdog
################################################################################
start_watchdog() {
print_section "Starting Watchdog"
if ! cd "${INSTALL_DIR}"; then
print_error "Cannot enter installation directory: ${INSTALL_DIR}"
exit 1
fi
# Validate Compose first and recreate only our service, never the project.
if ! $DC config -q; then
print_error "Compose configuration invalid; running containers unchanged"
exit 1
fi
print_info "Deploying watchdog container only..."
if ! $DC up -d --no-deps --force-recreate docker-container-watchdog; then
print_error "Watchdog deployment failed; check its Compose logs"
exit 1
fi
print_success "Watchdog container started"
}
################################################################################
# Verify
################################################################################
verify_deployment() {
print_section "Verifying Deployment"
local state health status attempts=0
while [ "$attempts" -lt 18 ]; do
state=$(docker inspect --format '{{.State.Status}}' "$CONTAINER_NAME" 2>/dev/null || true)
health=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$CONTAINER_NAME" 2>/dev/null || true)
status=$(docker ps -a --filter "name=^${CONTAINER_NAME}$" --format '{{.Status}}' 2>/dev/null || true)
if [ "$state" = "running" ] && { [ "$health" = "healthy" ] || [ "$health" = "none" ]; }; then
print_success "Container is running and healthy: ${status}"
break
fi
if [ "$state" = "exited" ] || [ "$state" = "dead" ]; then
break
fi
attempts=$((attempts + 1))
sleep 5
done
if [ "$state" != "running" ] || { [ "$health" != "healthy" ] && [ "$health" != "none" ]; }; then
print_error "Container ${CONTAINER_NAME} did not become healthy (state=${state:-unknown}, health=${health:-unknown})"
echo ""
echo " Check the logs for the reason:"
echo " $DC -f ${INSTALL_DIR}/docker-compose.yaml logs"
echo " docker logs ${CONTAINER_NAME}"
exit 1
fi
# Confirm the deployed release, not just that something is up: a stale
# image left over from a previous version would otherwise look healthy.
local RUNNING_IMAGE
RUNNING_IMAGE=$(docker inspect --format '{{.Config.Image}}' "$CONTAINER_NAME" 2>/dev/null || echo "")
local RUNNING_IMAGE_ID EXPECTED_IMAGE_ID
RUNNING_IMAGE_ID=$(docker inspect --format '{{.Image}}' "$CONTAINER_NAME" 2>/dev/null || true)
EXPECTED_IMAGE_ID=$(docker image inspect --format '{{.Id}}' "$IMAGE_NAME" 2>/dev/null || true)
if [ "$RUNNING_IMAGE" = "$IMAGE_NAME" ] && [ -n "$EXPECTED_IMAGE_ID" ] && [ "$RUNNING_IMAGE_ID" = "$EXPECTED_IMAGE_ID" ]; then
print_success "Container runs the verified image: $IMAGE_NAME"
else
print_error "Container is running '${RUNNING_IMAGE:-unknown}', expected '${IMAGE_NAME}'"
echo ""
echo " Check WATCHDOG_VERSION in ${INSTALL_DIR}/.env, then redeploy:"
echo " $DC -f ${INSTALL_DIR}/docker-compose.yaml up -d --force-recreate"
exit 1
fi
}
################################################################################
# Post-Installation Instructions
################################################################################
display_usage_instructions() {
print_section "Installation Complete!"
echo -e "${GREEN}✓ Installation successful!${NC}"
echo ""
echo -e "${BLUE}═══ Installation Summary ═══${NC}"
echo " • Installation directory : ${INSTALL_DIR}"
echo " • Container name : ${CONTAINER_NAME}"
echo " • Docker image : ${IMAGE_NAME}"
echo " • Secrets file : ${INSTALL_DIR}/.env"
echo " • Configuration : ${INSTALL_DIR}/watchdog-config.yaml"
echo " • Log file : ${INSTALL_DIR}/watchdog/watchdog.log"
echo ""
echo -e "${BLUE}═══ Common Commands ═══${NC}"
echo ""
echo -e "${GREEN}View live logs:${NC}"
echo " tail -f ${INSTALL_DIR}/watchdog/watchdog.log"
echo ""
echo -e "${GREEN}Container status:${NC}"
echo " $DC -f ${INSTALL_DIR}/docker-compose.yaml ps"
echo ""
echo -e "${GREEN}Restart watchdog:${NC}"
echo " $DC -f ${INSTALL_DIR}/docker-compose.yaml restart"
echo ""
echo -e "${GREEN}View stdout (Docker logs):${NC}"
echo " docker logs -f ${CONTAINER_NAME}"
echo ""
echo -e "${GREEN}Edit alert channels / thresholds:${NC}"
echo " sudoedit ${INSTALL_DIR}/watchdog-config.yaml"
echo " $DC -f ${INSTALL_DIR}/docker-compose.yaml restart"
echo ""
echo -e "${GREEN}Edit secrets (Slack / SMTP):${NC}"
echo " nano ${INSTALL_DIR}/.env"
echo " $DC -f ${INSTALL_DIR}/docker-compose.yaml up -d"
echo ""
echo -e "${GREEN}Uninstall:${NC}"
echo " sudo bash ${INSTALL_DIR}/uninstall.sh"
echo ""
}
################################################################################
# Main
################################################################################
main() {
print_header
check_prerequisites
load_docker_image || exit 1
setup_log_directory
configure_all || exit 1
start_watchdog
verify_deployment
display_usage_instructions
}
# Allow fake-Docker unit tests to source functions without invoking main.
if [[ "$BASH_SOURCE" == "$0" ]]; then
main "$@"
fi