fix: update env and PR template
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import json
|
||||
|
||||
from rolling_update import COMPOSE, ROOT, command
|
||||
from rolling_update import COMPOSE, ROOT, command, configured_replicas
|
||||
|
||||
|
||||
def main():
|
||||
@@ -29,7 +29,8 @@ def main():
|
||||
if service == "haproxy":
|
||||
assert "highload-lab3_data" not in networks
|
||||
if service == "api":
|
||||
assert not info["mounts"], "API must not mount persistent state"
|
||||
assert all(not mount["RW"] and mount["Type"] == "bind"
|
||||
for mount in info["mounts"]), "API mounts must be read-only configuration"
|
||||
records.append(
|
||||
{
|
||||
"service": service,
|
||||
@@ -40,14 +41,14 @@ def main():
|
||||
"public_ports": info["ports"],
|
||||
}
|
||||
)
|
||||
assert len([row for row in records if row["service"] == "api"]) == 2
|
||||
assert len([row for row in records if row["service"] == "api"]) == configured_replicas()
|
||||
ROOT.joinpath(".memory/grade4").mkdir(parents=True, exist_ok=True)
|
||||
ROOT.joinpath(".memory/grade4/resources.json").write_text(
|
||||
json.dumps(records, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps(records, indent=2))
|
||||
print(
|
||||
"PASS: effective CPU/RAM limits, two API replicas, private storage/API, isolated frontend"
|
||||
"PASS: effective CPU/RAM limits, configured API replicas, private storage/API, isolated frontend"
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -268,6 +268,7 @@ def command(args):
|
||||
|
||||
|
||||
def inspect_state():
|
||||
expected_replicas = int(json.loads(command(COMPOSE + ["config", "--format", "json"]))["services"]["api"]["deploy"]["replicas"])
|
||||
ids = command(COMPOSE + ["ps", "--all", "-q"]).split()
|
||||
rows = []
|
||||
template = (
|
||||
@@ -292,8 +293,8 @@ def inspect_state():
|
||||
)
|
||||
rows.append(row)
|
||||
api = [row for row in rows if row["service"] == "api"]
|
||||
assert len(api) == 2 and all(row["health"] == "healthy" for row in api), (
|
||||
"Two healthy API replicas required"
|
||||
assert len(api) == expected_replicas and all(row["health"] == "healthy" for row in api), (
|
||||
"All configured API replicas must be healthy"
|
||||
)
|
||||
for row in rows:
|
||||
assert row["cpu"] > 0 and row["memory"] > 0
|
||||
@@ -325,7 +326,7 @@ def inspect_state():
|
||||
for row in stats
|
||||
if row["pxname"] == "api_replicas" and row["svname"].startswith("api")
|
||||
]
|
||||
assert len(stats) == 2 and all(row["status"].startswith("UP") for row in stats)
|
||||
assert len(stats) == expected_replicas and all(row["status"].startswith("UP") for row in stats)
|
||||
addresses = {net["address"] for row in api for net in row["networks"].values()}
|
||||
assert all(row["addr"].split(":")[0] in addresses for row in stats)
|
||||
migration = command(
|
||||
|
||||
+61
-12
@@ -1,15 +1,64 @@
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
path = Path(__file__).resolve().parents[1] / ".env"
|
||||
if not path.exists():
|
||||
with path.open("x", encoding="utf-8") as file:
|
||||
file.write(
|
||||
"POSTGRES_DB=messenger\n"
|
||||
"POSTGRES_USER=messenger\n"
|
||||
f"POSTGRES_PASSWORD={secrets.token_hex(24)}\n"
|
||||
"SESSION_TTL_SECONDS=3600\n"
|
||||
)
|
||||
print("Created .env with a new local password.")
|
||||
else:
|
||||
print("Using existing .env.")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def read_values(path):
|
||||
values = {}
|
||||
if path.exists():
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip().strip("\"'")
|
||||
return values
|
||||
|
||||
def main():
|
||||
path = ROOT / ".env"
|
||||
existing = read_values(path)
|
||||
defaults = read_values(ROOT / ".env.example")
|
||||
defaults.update(POSTGRES_DB="messenger", POSTGRES_USER="messenger",
|
||||
POSTGRES_PASSWORD=secrets.token_hex(24))
|
||||
values = defaults | existing
|
||||
for name, lower, upper in (("APP_PORT", 1, 65535), ("API_REPLICAS", 2, 32),
|
||||
("SESSION_TTL_SECONDS", 1, 31536000),
|
||||
("IDEMPOTENCY_TTL_SECONDS", 1, 31536000)):
|
||||
try:
|
||||
valid = lower <= int(values[name]) <= upper
|
||||
except (ValueError, KeyError):
|
||||
valid = False
|
||||
if not valid:
|
||||
raise SystemExit(f"{name} must be between {lower} and {upper}")
|
||||
for name in ("POSTGRES_DB", "POSTGRES_USER", "POSTGRES_PASSWORD", "APP_HOST", "APP_ENV"):
|
||||
if not values[name]:
|
||||
raise SystemExit(f"{name} must not be empty")
|
||||
# Existing values, including credentials, are never replaced.
|
||||
missing = {key: value for key, value in values.items() if key not in existing}
|
||||
if missing:
|
||||
prefix = "\n" if path.exists() and path.stat().st_size else ""
|
||||
with path.open("a", encoding="utf-8") as file:
|
||||
file.write(prefix + "".join(f"{key}={value}\n" for key, value in missing.items()))
|
||||
os.chmod(path, 0o600)
|
||||
secret_dir = ROOT / "secrets"
|
||||
secret_dir.mkdir(mode=0o700, exist_ok=True)
|
||||
database_url = "postgres://{}:{}@db:5432/{}?sslmode=disable".format(
|
||||
quote(values["POSTGRES_USER"], safe=""), quote(values["POSTGRES_PASSWORD"], safe=""),
|
||||
quote(values["POSTGRES_DB"], safe=""))
|
||||
for name, content in (("DATABASE_URL_FILE", database_url),
|
||||
("CACHE_URL_FILE", "redis://redis:6379/0")):
|
||||
container_path = Path(values[name])
|
||||
if container_path.parent != Path("/run/secrets") or not container_path.name:
|
||||
raise SystemExit(f"{name} must name a file directly inside /run/secrets")
|
||||
target = secret_dir / ("database_url" if name == "DATABASE_URL_FILE" else "cache_url")
|
||||
if not target.exists():
|
||||
# Containers run as an unprivileged user; the private host directory
|
||||
# protects the files, while read permission lets the API consume them.
|
||||
with target.open("x", encoding="utf-8") as file:
|
||||
file.write(content + "\n")
|
||||
os.chmod(target, 0o644)
|
||||
print("Local .env and connection files ready; existing values and files preserved.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -24,6 +24,11 @@ def command(args, **kwargs):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
|
||||
|
||||
|
||||
def configured_replicas():
|
||||
config = json.loads(command(COMPOSE + ["config", "--format", "json"]))
|
||||
return int(config["services"]["api"]["deploy"]["replicas"])
|
||||
|
||||
|
||||
def containers():
|
||||
return command(COMPOSE + ["ps", "-q", "api"]).split()
|
||||
|
||||
@@ -79,8 +84,9 @@ def replace_all():
|
||||
with ROOT.joinpath(".memory/rolling.lock").open("w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
originals = containers()
|
||||
if len(originals) != 2:
|
||||
raise RuntimeError("Exactly two running API replicas are required")
|
||||
expected = configured_replicas()
|
||||
if expected < 2 or len(originals) != expected:
|
||||
raise RuntimeError("All configured API replicas must be running; minimum two")
|
||||
# One explicit migration job per operation, never one per replica.
|
||||
# Only backward-compatible migrations may be deployed while API is live.
|
||||
subprocess.run(
|
||||
@@ -90,13 +96,14 @@ def replace_all():
|
||||
for old in originals:
|
||||
before = containers()
|
||||
if (
|
||||
len(before) != 2
|
||||
or len([row for row in stats() if row["status"].startswith("UP")]) != 2
|
||||
len(before) != expected
|
||||
or len([row for row in stats() if row["status"].startswith("UP")]) != expected
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Both replicas must be ready before taking one out of service"
|
||||
)
|
||||
survivor = next(container for container in before if container != old)
|
||||
survivors = set(before) - {old}
|
||||
info = identity(old)
|
||||
addresses = {network["IPAddress"] for network in info["networks"].values()}
|
||||
matches = [row for row in stats() if row["addr"].split(":")[0] in addresses]
|
||||
@@ -139,16 +146,16 @@ def replace_all():
|
||||
finally:
|
||||
runtime(slot, "ready")
|
||||
after = containers()
|
||||
if len(after) != 2 or survivor not in after or old in after:
|
||||
if len(after) != expected or not survivors.issubset(after) or old in after:
|
||||
raise RuntimeError("Replacement changed the surviving container")
|
||||
new = next(container for container in after if container != survivor)
|
||||
new = next(container for container in after if container not in survivors)
|
||||
new_info = identity(new)
|
||||
new_addresses = {
|
||||
network["IPAddress"] for network in new_info["networks"].values()
|
||||
}
|
||||
wait_for(
|
||||
lambda: (
|
||||
len([row for row in stats() if row["status"].startswith("UP")]) == 2
|
||||
len([row for row in stats() if row["status"].startswith("UP")]) == expected
|
||||
and any(
|
||||
row["addr"].split(":")[0] in new_addresses
|
||||
and row["status"].startswith("UP")
|
||||
|
||||
Reference in New Issue
Block a user