Добавить вложения: S3-хранилище SeaweedFS, загрузку и скачивание через API, сверщик PostgreSQL и S3
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / 'secrets'
|
||||
|
||||
|
||||
def write(name, value):
|
||||
path = SECRETS / name
|
||||
if path.exists():
|
||||
print('keep existing secrets/%s' % name)
|
||||
return path.read_text(encoding='utf-8').strip()
|
||||
path.write_text(value + '\n', encoding='utf-8')
|
||||
os.chmod(path, 0o644)
|
||||
print('created secrets/%s' % name)
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
SECRETS.mkdir(exist_ok=True)
|
||||
password = write('postgres_password', secrets.token_hex(24))
|
||||
write('database_url', 'postgresql://messenger:%s@postgres:5432/messenger' % password)
|
||||
bucket = 'messenger-attachments'
|
||||
rights = {'admin': ['Admin', 'Read', 'List', 'Tagging', 'Write'],
|
||||
'api': ['Read:' + bucket, 'Write:' + bucket],
|
||||
'reconciler': ['Read:' + bucket, 'List:' + bucket, 'Write:' + bucket]}
|
||||
identities = []
|
||||
for role, actions in rights.items():
|
||||
key = write('s3_%s_access_key_id' % role, role + '-' + secrets.token_hex(8))
|
||||
secret = write('s3_%s_secret_access_key' % role, secrets.token_hex(24))
|
||||
identities.append({'name': role, 'credentials': [{'accessKey': key, 'secretKey': secret}], 'actions': actions})
|
||||
write('s3_config.json', json.dumps({'identities': identities}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose stop api || exit /b 1
|
||||
docker compose restart postgres valkey s3 || exit /b 1
|
||||
docker compose up -d --no-build --no-recreate --wait postgres valkey s3 || exit /b 1
|
||||
docker compose start api || exit /b 1
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop api
|
||||
docker compose restart postgres valkey s3
|
||||
docker compose up -d --no-build --no-recreate --wait postgres valkey s3
|
||||
docker compose start api
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Поочерёдная замена API-реплик без остановки сервиса.
|
||||
|
||||
python scripts/rolling_update.py # пересобрать образ и заменить реплики по одной
|
||||
python scripts/rolling_update.py --no-build # заменить на текущий образ
|
||||
|
||||
1. Один раз применяет миграции (отдельный контейнер migrate; совместимые, только добавляющие изменения).
|
||||
2. Для каждой старой реплики: поднимает одну новую (--scale +1, --no-recreate), ждёт, пока LB начнёт
|
||||
отправлять на неё трафик, затем штатно останавливает старую (SIGTERM → вывод из ротации → завершение)
|
||||
и удаляет её контейнер. Число реплик в ротации не опускается ниже исходного.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8080').rstrip('/')
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def running_api():
|
||||
return compose('ps', '-q', 'api').split()
|
||||
|
||||
|
||||
def instance_of_next_response():
|
||||
try:
|
||||
with urllib.request.urlopen(BASE_URL + '/health/ready', timeout=2) as response:
|
||||
return response.headers.get('X-Instance-Id')
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def wait_in_rotation(container, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if instance_of_next_response() == container[:12]:
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise SystemExit('new replica %s did not enter LB rotation' % container[:12])
|
||||
|
||||
|
||||
def image_of(container):
|
||||
return subprocess.run(['docker', 'inspect', '-f', '{{.Image}}', container], capture_output=True, text=True).stdout.strip()[7:19]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--no-build', action='store_true')
|
||||
args = parser.parse_args()
|
||||
old = running_api()
|
||||
print('old replicas:', ', '.join('%s(image %s)' % (c[:12], image_of(c)) for c in old))
|
||||
if not args.no_build:
|
||||
compose('build', 'api')
|
||||
compose('run', '--rm', '--no-deps', 'migrate')
|
||||
print('migrations applied once')
|
||||
for container in old:
|
||||
before = set(running_api())
|
||||
compose('up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=%d' % (len(before) + 1), 'api')
|
||||
new = (set(running_api()) - before).pop()
|
||||
started = time.monotonic()
|
||||
wait_in_rotation(new)
|
||||
print('+ %s (image %s) in rotation after %.1fs' % (new[:12], image_of(new), time.monotonic() - started))
|
||||
started = time.monotonic()
|
||||
subprocess.run(['docker', 'stop', '-t', '15', container], check=True, capture_output=True)
|
||||
subprocess.run(['docker', 'rm', container], check=True, capture_output=True)
|
||||
print('- %s stopped and removed after %.1fs' % (container[:12], time.monotonic() - started))
|
||||
print('new replicas:', ', '.join('%s(image %s)' % (c[:12], image_of(c)) for c in running_api()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,11 @@
|
||||
@echo off
|
||||
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
|
||||
cd /d "%~dp0.."
|
||||
for /f %%i in ('docker compose ps -q api') do (
|
||||
echo %%i| findstr /b /i "%TARGET_INSTANCE_ID%" >nul && (
|
||||
docker stop -t 10 %%i >nul
|
||||
exit /b 0
|
||||
)
|
||||
)
|
||||
echo no running api replica matches TARGET_INSTANCE_ID 1>&2
|
||||
exit /b 1
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
for id in $(docker compose ps -q api); do
|
||||
case "$id" in
|
||||
"$TARGET_INSTANCE_ID"*)
|
||||
docker stop -t 10 "$id" >/dev/null
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
echo "no running api replica matches TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user