|
| 1 | +"""Add and backfill branch.db_port |
| 2 | +
|
| 3 | +Revision ID: 2b4e8f1a6c03 |
| 4 | +Revises: f4f677e4e9b9 |
| 5 | +Create Date: 2026-03-19 00:00:00.000000 |
| 6 | +
|
| 7 | +""" |
| 8 | +import logging |
| 9 | +import os |
| 10 | +from typing import Sequence, Union |
| 11 | + |
| 12 | +from alembic import op |
| 13 | +import sqlalchemy as sa |
| 14 | +from kubernetes import client as kubernetes_client |
| 15 | +from kubernetes import config as kubernetes_config |
| 16 | +from kubernetes.config.config_exception import ConfigException |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +# revision identifiers, used by Alembic. |
| 21 | +revision: str = '2b4e8f1a6c03' |
| 22 | +down_revision: Union[str, Sequence[str], None] = 'f4f677e4e9b9' |
| 23 | +branch_labels: Union[str, Sequence[str], None] = None |
| 24 | +depends_on: Union[str, Sequence[str], None] = None |
| 25 | + |
| 26 | +_CHART_NAME = "vela" |
| 27 | + |
| 28 | + |
| 29 | +def _ensure_kube_client_config() -> None: |
| 30 | + try: |
| 31 | + kubernetes_config.load_incluster_config() |
| 32 | + except ConfigException: |
| 33 | + try: |
| 34 | + kubernetes_config.load_kube_config() |
| 35 | + except ConfigException as exc: |
| 36 | + raise RuntimeError("Kubernetes client not configured. Mount kubeconfig or run in-cluster.") from exc |
| 37 | + |
| 38 | + |
| 39 | +def _deployment_namespace(branch_id: str) -> str: |
| 40 | + prefix = os.environ.get("VELA_DEPLOYMENT_NAMESPACE_PREFIX", "vela") |
| 41 | + return f"{prefix}-{branch_id.lower()}" if prefix else branch_id.lower() |
| 42 | + |
| 43 | + |
| 44 | +def _release_fullname() -> str: |
| 45 | + release = os.environ.get("VELA_DEPLOYMENT_RELEASE_NAME", "vela") |
| 46 | + return release if _CHART_NAME in release else f"{release}-{_CHART_NAME}" |
| 47 | + |
| 48 | + |
| 49 | +def _branch_service_name(component: str) -> str: |
| 50 | + return f"{_release_fullname()}-{component}" |
| 51 | + |
| 52 | + |
| 53 | +def _get_node_port(branch_id: str) -> int | None: |
| 54 | + core_v1 = kubernetes_client.CoreV1Api() |
| 55 | + namespace = _deployment_namespace(branch_id) |
| 56 | + for service_name in (_branch_service_name("pgbouncer"), _branch_service_name("db")): |
| 57 | + try: |
| 58 | + svc = core_v1.read_namespaced_service(name=service_name, namespace=namespace) |
| 59 | + ports = svc.spec.ports |
| 60 | + if ports and ports[0].node_port: |
| 61 | + return ports[0].node_port |
| 62 | + except kubernetes_client.exceptions.ApiException as exc: |
| 63 | + if exc.status == 404: |
| 64 | + continue |
| 65 | + raise |
| 66 | + return None |
| 67 | + |
| 68 | + |
| 69 | +def upgrade() -> None: |
| 70 | + """Upgrade schema.""" |
| 71 | + op.add_column( |
| 72 | + 'branch', |
| 73 | + sa.Column('db_port', sa.Integer(), nullable=True), |
| 74 | + ) |
| 75 | + |
| 76 | + bind = op.get_bind() |
| 77 | + branch_rows = bind.execute( |
| 78 | + sa.text("SELECT id::text AS id FROM branch") |
| 79 | + ).mappings().all() |
| 80 | + |
| 81 | + if not branch_rows: |
| 82 | + return |
| 83 | + |
| 84 | + _ensure_kube_client_config() |
| 85 | + |
| 86 | + updates = [] |
| 87 | + for row in branch_rows: |
| 88 | + port = _get_node_port(row["id"]) |
| 89 | + if port is None: |
| 90 | + logger.warning("Could not resolve db_port for branch %s — skipping", row["id"]) |
| 91 | + continue |
| 92 | + updates.append({"id": row["id"], "db_port": port}) |
| 93 | + |
| 94 | + if updates: |
| 95 | + bind.execute( |
| 96 | + sa.text( |
| 97 | + """ |
| 98 | + UPDATE branch |
| 99 | + SET db_port = :db_port |
| 100 | + WHERE id = CAST(:id AS uuid) |
| 101 | + """ |
| 102 | + ), |
| 103 | + updates, |
| 104 | + ) |
| 105 | + |
| 106 | + |
| 107 | +def downgrade() -> None: |
| 108 | + """Downgrade schema.""" |
| 109 | + op.drop_column('branch', 'db_port') |
0 commit comments