Files
buryan-infra/ops/vps/vps-cache-assets.sh
T
architect c985c0617b
lint / hygiene (push) Failing after 30s
lint / hygiene (pull_request) Failing after 21s
standard / check (push) Successful in 9s
standard / check (pull_request) Successful in 14s
[INFRA] migrate active old VPS 193.233.210.184 to 45.133.209.253
2026-12-02 18:00:21 +03:00

148 lines
6.8 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# ============================================================
# vps-cache-assets.sh — кэш файлов страницы входа на VPS
# ============================================================
# ЗАДАЧА 2.1. ЗАМЕРЕНО: страница входа грузит 1,5 МБ файлов, и каждый
# идёт через туннель Tailscale в дом и обратно:
# flow_background.jpg 642 КБ 0,75 с
# FlowInterface.js 408 КБ 0,90 с
# poly.js 469 КБ 0,69 с
# + мелочь
# Итого около трёх секунд только на файлы, плюс сама страница.
#
# ЧТО ДЕЛАЮ: кэширую статические файлы НА VPS. Тогда повторная загрузка
# берёт их с диска VPS, а не едет в дом за каждым.
#
# Осторожность:
# * кэширую ТОЛЬКО /static/ и /media/ — это статика;
# * страницы входа (динамика) НЕ кэширую: там токены и сессии;
# * копия конфигурации, проверка nginx -t, откат при ошибке;
# * в ответ добавляю заголовок X-Cache-Status — чтобы видеть, работает ли.
# ============================================================
set -uo pipefail
VPS=45.133.209.253
CONF=/etc/nginx/conf.d/buryans-all.conf
CACHE_CONF=/etc/nginx/conf.d/00-proxy-cache.conf
STAMP=$(date +%Y%m%d_%H%M%S)
echo "=== 1. КОПИИ ==="
ssh -o BatchMode=yes root@$VPS "cp -p $CONF $CONF.before-cache-$STAMP && echo ' конфигурация сохранена'" 2>&1 | sed 's/^/ /'
echo
echo "=== 2. КАТАЛОГ КЭША ==="
ssh -o BatchMode=yes root@$VPS 'mkdir -p /var/cache/nginx/authentik && chown -R www-data:www-data /var/cache/nginx && ls -ld /var/cache/nginx/authentik' 2>&1 | sed 's/^/ /'
echo
echo "=== 3. ЗОНА КЭША ==="
ssh -o BatchMode=yes root@$VPS "cat > $CACHE_CONF" <<'EOF'
# Зона кэша для статических файлов страницы входа.
# Задача 2.1: файлы грузятся через туннель в дом, каждый по 0,3-0,9 с.
# Кэш отдаёт их с диска VPS.
proxy_cache_path /var/cache/nginx/authentik
levels=1:2
keys_zone=auth_cache:50m
max_size=1g
inactive=7d
use_temp_path=off;
EOF
ssh -o BatchMode=yes root@$VPS "cat $CACHE_CONF" 2>&1 | sed 's/^/ /'
echo
echo "=== 4. ВСТАВЛЯЮ КЭШ В БЛОКИ ВХОДА ==="
ssh -o BatchMode=yes root@$VPS 'python3 - <<'"'"'PYEOF'"'"'
import io, re
p = "/etc/nginx/conf.d/buryans-all.conf"
t = io.open(p, encoding="utf-8").read()
LOCATION = """ # Кэш статики: файлы не едут каждый раз в дом через туннель
location /static/ {
proxy_cache auth_cache;
proxy_cache_valid 200 7d;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_ignore_headers Cache-Control Expires Set-Cookie;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://192.168.1.114:9000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /media/ {
proxy_cache auth_cache;
proxy_cache_valid 200 7d;
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_use_stale error timeout updating;
proxy_ignore_headers Cache-Control Expires Set-Cookie;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://192.168.1.114:9000;
proxy_set_header Host $host;
}
"""
# вставляю перед "location / {" в блоках authentik и admin
targets = ["server_name authentik.buryans.ru;", "server_name admin.buryans.ru;"]
changed = 0
for name in targets:
idx = t.find(name)
if idx == -1:
print(" не нашёл блок %s" % name)
continue
# ищу первую "location / {" после этого места
loc = t.find("location / {", idx)
if loc == -1:
print(" не нашёл location / для %s" % name)
continue
if "proxy_cache auth_cache;" in t[idx:loc]:
print(" кэш уже есть в %s" % name)
continue
# отступаю до начала строки
line_start = t.rfind("\n", 0, loc) + 1
t = t[:line_start] + LOCATION + t[line_start:]
changed += 1
print(" кэш добавлен в %s" % name)
if changed:
io.open(p, "w", encoding="utf-8").write(t)
print(" изменено блоков: %d" % changed)
PYEOF' 2>&1 | sed 's/^/ /'
echo
echo "=== 5. ПРОВЕРКА КОНФИГУРАЦИИ ==="
if ssh -o BatchMode=yes root@$VPS 'nginx -t 2>&1' | grep -q "syntax is ok"; then
echo " синтаксис верный"
ssh -o BatchMode=yes root@$VPS 'nginx -t 2>&1' | tail -2 | sed 's/^/ /'
else
echo " ОШИБКА — откатываю"
ssh -o BatchMode=yes root@$VPS "cp -p $CONF.before-cache-$STAMP $CONF && rm -f $CACHE_CONF && nginx -t 2>&1 | tail -2" | sed 's/^/ /'
exit 1
fi
echo
echo "=== 6. ПРИМЕНЯЮ ==="
ssh -o BatchMode=yes root@$VPS 'systemctl reload nginx && echo " nginx перезагружен"' 2>&1 | sed 's/^/ /'
echo
echo "=== 7. ПРОВЕРКА: ПЕРВАЯ И ВТОРАЯ ЗАГРУЗКА ==="
for i in 1 2 3; do
r=$(ssh -o BatchMode=yes root@$VPS 'curl -s -o /dev/null -D - -k --max-time 20 "https://authentik.buryans.ru/static/dist/poly-2025.2.4.js" 2>/dev/null | grep -i "x-cache-status\|time"' 2>/dev/null)
t=$(ssh -o BatchMode=yes root@$VPS 'curl -s -o /dev/null -w "%{time_total}" -k --max-time 20 "https://authentik.buryans.ru/static/dist/poly-2025.2.4.js" 2>/dev/null')
st=$(ssh -o BatchMode=yes root@$VPS 'curl -s -o /dev/null -D - -k --max-time 20 "https://authentik.buryans.ru/static/dist/poly-2025.2.4.js" 2>/dev/null | grep -i "x-cache-status" | tr -d "\r"' 2>/dev/null)
printf ' попытка %d: %s, время %s с\n' "$i" "${st:-статус неизвестен}" "${t:-—}"
done
echo
echo "=== 8. ОБЩЕЕ ВРЕМЯ СТРАНИЦЫ ==="
ssh -o BatchMode=yes root@$VPS 'for i in 1 2; do
t=$(curl -s -o /dev/null -w "%{time_total}" --max-time 20 -k https://authentik.buryans.ru/ 2>/dev/null)
echo " страница (попытка $i): ${t}s"
done' 2>&1 | sed 's/^/ /'
echo
echo "============================================================"
echo " Откат:"
echo " cp $CONF.before-cache-$STAMP $CONF && rm -f $CACHE_CONF && nginx -t && systemctl reload nginx"
echo "============================================================"