Files
mtusi2026lab4/scripts/rolling_update.py
T

78 lines
3.3 KiB
Python

"""Поочерёдная замена 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())