Files
mtusi2026lab4/scripts/init_env.py
T
2026-10-18 18:06:27 +03:00

67 lines
3.2 KiB
Python

import os
import secrets
from pathlib import Path
from urllib.parse import quote
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"),
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32))):
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_FILE":"database_url", "CACHE_URL_FILE":"cache_url", "S3_ACCESS_KEY_ID_FILE":"s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE":"s3_secret_access_key"}[name]
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()