Repository navigation
Expand file tree
/
Copy pathprod-setup.sh
More file actions
executable file
·273 lines (254 loc) · 12.4 KB
/
Copy pathprod-setup.sh
File metadata and controls
executable file
·273 lines (254 loc) · 12.4 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
#!/usr/bin/env bash
# One-time (idempotent) host preparation for the PRODUCTION server. Run as root
# on the server, from the deployed repo directory, AFTER .env.production exists:
#
# source scripts/prod.env
# sudo -E ./scripts/prod-setup.sh
#
# It:
# 1. installs cifs-utils (needed to mount the Storage Box over SMB/CIFS) and,
# when the kernel lacks nls_utf8, Ubuntu's HWE kernel,
# 2. adds a 2 GB swap file if the host has none (safety net on a 4 GB box),
# 3. creates the per-volume directories on the attached volume (${DATA_ROOT}),
# 4. creates + validates the immich/ and seafile/ subfolders on the Storage Box
# (a CIFS mount of a missing subpath fails, so they must exist first),
# 5. enables zswap with the zsmalloc pool and the lzo-rle compressor
# (compresses swap pages in RAM before hitting the swapfile, cutting disk
# I/O under memory pressure; persisted via GRUB cmdline),
# 6. writes /etc/docker/daemon.json for log rotation and live-restore,
# 7. pins the Docker engine to ${DOCKER_MAJOR}.x and lets unattended-upgrades
# apply that line's patch releases,
# 8. installs + enables the systemd timers (daily backup, weekly restore check,
# mount watchdog, weekly Docker-major check),
# 9. caps the systemd journal at 1 GB,
# 10. installs fail2ban and turns off X11, TCP and agent forwarding in sshd.
set -euo pipefail
cd "$(dirname "$0")/.."
ENV_FILE="${ENV_FILE:-.env.production}"
[[ -f "$ENV_FILE" ]] || { echo "$ENV_FILE not found — run: source scripts/prod.env" >&2; exit 1; }
set -a; . "$ENV_FILE"; set +a
if [[ $EUID -ne 0 ]]; then echo "Run as root (sudo -E $0)." >&2; exit 1; fi
echo "==> [1/10] cifs-utils + sqlite3 + jq (sqlite3 = consistent Vaultwarden backups) + nls_utf8"
need=()
command -v mount.cifs >/dev/null 2>&1 || need+=(cifs-utils)
command -v sqlite3 >/dev/null 2>&1 || need+=(sqlite3)
# jq merges daemon.json in step 6 rather than clobbering keys this script does
# not own.
command -v jq >/dev/null 2>&1 || need+=(jq)
if [[ ${#need[@]} -eq 0 ]]; then
echo " already installed."
else
apt-get update -qq && apt-get install -y -qq "${need[@]}"
echo " installed: ${need[*]}"
fi
# navidrome_music mounts with iocharset=utf8 (docker-compose.yml says why), which fails
# without the kernel's nls_utf8. Ubuntu's GA cloud kernel keeps it in
# linux-modules-extra; the HWE kernel ships it in its base modules and its meta
# package follows kernel updates.
has_nls_utf8() { modinfo -k "$1" nls_utf8 >/dev/null 2>&1; }
newest_kernel() { ls /lib/modules | sort -V | tail -n1; }
reboot_needed=0
if has_nls_utf8 "$(uname -r)"; then
echo " nls_utf8 available."
else
if ! has_nls_utf8 "$(newest_kernel)"; then
hwe="linux-image-virtual-hwe-$(. /etc/os-release && echo "$VERSION_ID")"
apt-get update -qq
if ! apt-cache show "$hwe" >/dev/null 2>&1; then
echo " kernel $(uname -r) has no nls_utf8 and there is no $hwe;" >&2
echo " install a kernel that ships the module, then re-run." >&2
exit 1
fi
apt-get install -y -qq "$hwe"
has_nls_utf8 "$(newest_kernel)" || { echo " $hwe installed but has no nls_utf8." >&2; exit 1; }
echo " installed $hwe."
fi
reboot_needed=1
fi
echo "==> [2/10] swap"
if [[ -n "$(swapon --show --noheadings 2>/dev/null)" ]]; then
echo " swap already active — leaving as is."
else
fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048
chmod 600 /swapfile
mkswap /swapfile >/dev/null
swapon /swapfile
grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
echo " created /swapfile (2G) and enabled it."
fi
echo "==> [3/10] data directories on the attached volume (${DATA_ROOT})"
for d in caddy_data vaultwarden_data immich_db immich_modelcache \
immich_thumbs immich_encoded seafile_db seafile_data navidrome_data; do
mkdir -p "${DATA_ROOT}/${d}"
done
echo " created: ${DATA_ROOT}/{caddy_data,vaultwarden_data,immich_db,immich_modelcache,immich_thumbs,immich_encoded,seafile_db,seafile_data,navidrome_data}"
echo "==> [4/10] Storage Box subfolders (//${SB_HOST}/${SB_SHARE}/{immich,seafile,music/${NAVIDROME_LIBRARY}})"
if [[ -z "${SB_PASSWORD:-}" || "$SB_PASSWORD" == "CHANGEME" ]]; then
echo " SB_PASSWORD is not set in ${ENV_FILE} — set it, then re-run." >&2
exit 1
fi
tmpmnt="$(mktemp -d)"
trap 'umount "$tmpmnt" 2>/dev/null || true; rmdir "$tmpmnt" 2>/dev/null || true' EXIT
mount -t cifs "//${SB_HOST}/${SB_SHARE}" "$tmpmnt" \
-o "username=${SB_USER},password=${SB_PASSWORD},vers=${SB_SMB_VERS},seal"
mkdir -p "$tmpmnt/immich" "$tmpmnt/seafile" "$tmpmnt/music/${NAVIDROME_LIBRARY:?}"
echo " Storage Box reachable; immich/, seafile/ and music/${NAVIDROME_LIBRARY}/ present."
echo "==> [5/10] zswap (compress swap pages in RAM, reduce swapfile I/O)"
# zswap's zpool/compressor are module params, not sysctls: this write covers the
# running kernel, the cmdline below covers every boot after.
# Kernels from 6.15 on have no zpool parameter: zsmalloc is their only pool.
zswap_params=(enabled=Y zpool=zsmalloc compressor=lzo-rle)
cmdline=()
for p in "${zswap_params[@]}"; do
key="${p%%=*}"; want="${p#*=}"
sysfs="/sys/module/zswap/parameters/${key}"
[[ -e "$sysfs" ]] || { echo " zswap.${key} not in this kernel — skipping."; continue; }
if [[ "$want" == Y ]]; then cmdline+=("zswap.${key}=1"); else cmdline+=("zswap.${key}=${want}"); fi
[[ -w "$sysfs" ]] || { echo " $sysfs not writable — skipping." >&2; continue; }
if [[ "$(cat "$sysfs")" == "$want" ]]; then
echo " zswap.${key} already $want."
else
echo "$want" > "$sysfs"
echo " zswap.${key} set to $want for this boot."
fi
done
# Persist the same parameters on the kernel cmdline. grub-mkconfig sources
# /etc/default/grub.d/*.cfg after /etc/default/grub, so a drop-in appends to the
# cmdline without editing the distro's file. Params repeat harmlessly if that
# file already sets one — for module params the last occurrence wins.
grub_dropin=/etc/default/grub.d/99-private-cloud.cfg
grub_before="$(cat "$grub_dropin" 2>/dev/null || true)"
mkdir -p "$(dirname "$grub_dropin")"
cat > "$grub_dropin" <<EOF
# zsmalloc packs more than two compressed pages per frame and lzo-rle handles
# byte runs; together they measured ~20% less pool than the kernel's zbud/lzo.
GRUB_CMDLINE_LINUX_DEFAULT="\$GRUB_CMDLINE_LINUX_DEFAULT ${cmdline[*]}"
EOF
if [[ "$grub_before" == "$(cat "$grub_dropin")" ]]; then
echo " $grub_dropin unchanged."
else
update-grub 2>&1 | grep -E 'Generating|done|error' || true
echo " written $grub_dropin — zswap settings will persist across reboots."
fi
echo "==> [6/10] Docker daemon.json (log rotation + live-restore)"
# live-restore keeps containers running while dockerd restarts, so the upgrades
# step 7 hands to unattended-upgrades do not bounce the stack.
daemon_json=/etc/docker/daemon.json
mkdir -p "$(dirname "$daemon_json")"
# Merge rather than overwrite: keys this script does not own are preserved.
before="$(jq -S . "$daemon_json" 2>/dev/null || echo '{}')"
after="$(jq -S '. + {
"log-driver": "local",
"log-opts": {"max-size": "10m", "max-file": "3"},
"live-restore": true
}' <<<"$before")"
if [[ "$before" == "$after" ]]; then
echo " $daemon_json already has the wanted settings."
else
printf '%s\n' "$after" > "$daemon_json"
echo " written $daemon_json."
# reload picks up log-opts and live-restore without stopping containers;
# a restart is only needed when the daemon is not running yet.
if systemctl is-active --quiet docker; then
systemctl reload docker && echo " reloaded docker (containers untouched)."
fi
fi
echo "==> [7/10] Docker upgrade policy (pin ${DOCKER_MAJOR:-?}.x, patch it unattended)"
: "${DOCKER_MAJOR:?not set in ${ENV_FILE}}"
: "${CONTAINERD_MAJOR:?not set in ${ENV_FILE}}"
codename="$(. /etc/os-release && echo "$VERSION_CODENAME")"
pin=/etc/apt/preferences.d/docker-major.pref
cat > "$pin" <<EOF
# Managed by scripts/prod-setup.sh — edit DOCKER_MAJOR/CONTAINERD_MAJOR in the
# env file (which explains the policy) and re-run, instead of changing this file.
Package: docker-ce docker-ce-cli docker-ce-rootless-extras
Pin: version 5:${DOCKER_MAJOR}.*
Pin-Priority: 1000
Package: containerd.io
Pin: version ${CONTAINERD_MAJOR}.*
Pin-Priority: 1000
EOF
echo " pinned docker-ce to ${DOCKER_MAJOR}.x, containerd.io to ${CONTAINERD_MAJOR}.x."
uu=/etc/apt/apt.conf.d/52unattended-upgrades-docker
installed="$(dpkg-query -W -f='${Version}' docker-ce 2>/dev/null | sed 's/^[0-9]*://' | cut -d. -f1 || true)"
# Withhold the allowed-origin file while the installed major is behind the pin:
# together they would let unattended-upgrades cross the major on its own. The
# pin above is already written (it only ever constrains), so the manual upgrade
# below resolves to the newest ${DOCKER_MAJOR}.x without naming a version.
if [[ -n "$installed" && "$installed" != "$DOCKER_MAJOR" ]]; then
rm -f "$uu"
echo " docker-ce ${installed}.x is installed, but the pin targets ${DOCKER_MAJOR}.x."
echo " NOT handing Docker to unattended-upgrades yet — it would cross that major"
echo " unwatched. With a fresh backup, in a window you are watching, run:"
echo " apt-get install -y docker-ce docker-ce-cli docker-ce-rootless-extras containerd.io"
echo " then re-run this script to finish enabling automatic patch upgrades."
else
cat > "$uu" <<EOF
// Managed by scripts/prod-setup.sh.
//
// Docker's repo is o=Docker, which the stock Allowed-Origins list does not
// cover — without this the engine would never be patched automatically. A
// second declaration APPENDS to the list, so the Ubuntu origins still apply.
Unattended-Upgrade::Allowed-Origins {
"Docker:${codename}";
};
EOF
echo " unattended-upgrades may now patch Docker within ${DOCKER_MAJOR}.x."
fi
echo "==> [8/10] systemd timers (daily backup, weekly restore check, mount watchdog, docker-major check)"
# Refreshes the unit files from the repo, so re-running after an update picks up
# any change. enable --now is idempotent.
# pc-notify-failure@.service is a template pulled in by OnFailure= — installed,
# never enabled.
cp scripts/systemd/pc-backup.* scripts/systemd/pc-restore-check.* \
scripts/systemd/pc-mount-watchdog.* scripts/systemd/pc-docker-major-check.* \
scripts/systemd/pc-notify-failure@.service \
/etc/systemd/system/
systemctl daemon-reload
systemctl enable --now pc-backup.timer pc-restore-check.timer pc-mount-watchdog.timer \
pc-docker-major-check.timer
echo " installed + enabled: pc-backup.timer, pc-restore-check.timer, pc-mount-watchdog.timer, pc-docker-major-check.timer"
echo "==> [9/10] journald size cap"
# journald's default cap is 10% of the filesystem (at most 4 GB); on the root
# filesystem that space is shared with Docker's images.
journald_dropin=/etc/systemd/journald.conf.d/size.conf
journald_want=$'[Journal]\nSystemMaxUse=1G'
if [[ "$(cat "$journald_dropin" 2>/dev/null)" == "$journald_want" ]]; then
echo " $journald_dropin unchanged."
else
mkdir -p "$(dirname "$journald_dropin")"
printf '%s\n' "$journald_want" > "$journald_dropin"
systemctl restart systemd-journald
echo " written $journald_dropin and restarted journald."
fi
echo "==> [10/10] fail2ban + sshd forwarding"
if command -v fail2ban-client >/dev/null 2>&1; then
echo " fail2ban already installed."
else
apt-get update -qq && apt-get install -y -qq fail2ban
echo " installed fail2ban."
fi
# The Debian packaging enables the sshd jail on its own; ban timings are stock.
systemctl enable --now fail2ban >/dev/null 2>&1
echo " fail2ban enabled."
# sshd here carries admin shells and the rsync deploy, none of which forward.
# sshd takes the FIRST occurrence of a keyword and Ubuntu's sshd_config includes
# this directory above its own X11Forwarding line, so the drop-in wins.
sshd_dropin=/etc/ssh/sshd_config.d/99-private-cloud.conf
sshd_want=$'X11Forwarding no\nAllowTcpForwarding no\nAllowAgentForwarding no'
if [[ "$(cat "$sshd_dropin" 2>/dev/null)" == "$sshd_want" ]]; then
echo " $sshd_dropin unchanged."
else
mkdir -p "$(dirname "$sshd_dropin")"
printf '%s\n' "$sshd_want" > "$sshd_dropin"
# Validate before reloading: reload on a rejected file would drop sshd.
sshd -t || { rm -f "$sshd_dropin"; echo " sshd rejected the drop-in — removed." >&2; exit 1; }
systemctl reload ssh
echo " written $sshd_dropin and reloaded sshd."
fi
echo
if (( reboot_needed )); then
echo "Host prepared. Reboot onto kernel $(newest_kernel) first: the music mount needs its nls_utf8."
else
echo "Host prepared. Next: source scripts/prod.env && docker compose up -d"
fi