Files
mtusi2026lab5/scripts/rolling-update.cmd
T

52 lines
1.7 KiB
Batchfile

@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem Grade-4 rolling replacement: replace API containers one-by-one under LB.
rem Usage: scripts\rolling-update.cmd
cd /d "%~dp0\.."
set "REPLICAS=%API_REPLICAS%"
if "%REPLICAS%"=="" set "REPLICAS=2"
set "URL=http://127.0.0.1:8080/health/ready"
set "IDS="
for /f "usebackq delims=" %%I in (`docker compose --env-file .env ps -q api`) do set "IDS=!IDS! %%I"
set "KNOWN=%IDS%"
set /a COUNT=0
for %%I in (%IDS%) do (
set /a COUNT+=1
echo rolling: replacing %%I
rem -t 15 = stop_grace_period: the replica drains ~3 s before it exits.
docker stop -t 15 %%I >nul || exit /b 1
docker rm %%I >nul || exit /b 1
rem --no-recreate: the surviving replica keeps serving even if the image/config changed.
docker compose --env-file .env up -d --no-deps --no-recreate --scale api=%REPLICAS% api || exit /b 1
call :wait_new || exit /b 1
)
echo rolling update finished (%COUNT% steps, scale=%REPLICAS%)
exit /b 0
:wait_new
set "NEW="
for /f "usebackq delims=" %%J in (`docker compose --env-file .env ps -q api`) do (
if "!KNOWN:%%J=!"=="!KNOWN!" set "NEW=%%J"
)
if "%NEW%"=="" (
echo rolling: expected one new replica >&2
exit /b 1
)
set "KNOWN=%KNOWN% %NEW%"
for /f "usebackq delims=" %%H in (`docker inspect -f "{{.Config.Hostname}}" %NEW%`) do set "HOST=%%H"
rem Public ready is 200 while the other replica serves; wait until the LB routes to the new one.
set /a TRIES=0
:poll
curl.exe -s -D - -o NUL "%URL%" | findstr /I /B /C:"x-instance-id: %HOST%" >nul && goto ready
set /a TRIES+=1
if %TRIES% geq 90 (
echo rolling: %HOST% not in LB rotation >&2
exit /b 1
)
ping -n 2 127.0.0.1 >nul
goto poll
:ready
echo rolling: step %COUNT% ready (%HOST%)
exit /b 0