Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions api/src/database/services/organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from sqlalchemy import Select, func, delete, select
from sqlalchemy import update as sql_update
from sqlalchemy.orm import defer, load_only, joinedload, selectinload, contains_eager
from src.kubernetes import databases
from src.kubernetes import client, databases
from collections.abc import Sequence
from src.models.tags import TagIcon, TagKind
from src.environments import env
Expand All @@ -20,7 +20,6 @@
from botocore.exceptions import ClientError, BotoCoreError
from src.models.statuses import Status
from src.database.services import operations
from src.kubernetes.client import Kubernetes
from src.models.operations import OperationKind
from src.models.pagination import Pagination
from sqlalchemy.ext.asyncio import AsyncSession
Expand Down Expand Up @@ -468,9 +467,9 @@ async def update_usage(session: AsyncSession, organization_id: UUID, user_id: UU
)
if compute is None:
raise HTTPException(status_code=404, detail="Organization not found")
cluster = Kubernetes(compute.kubeconfig)
try:
async with asyncio.timeout(15):
cluster = await client.api(compute.kubeconfig)
provisioned = await databases.provisioned_storage_bytes(cluster, organization_id)
except NotFoundError as exc:
if organization.status != Status.failed or organization.provisioned_at is not None:
Expand Down
11 changes: 10 additions & 1 deletion api/src/database/services/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,16 @@ async def member(session: AsyncSession, solution: Solution, user_id: UUID) -> di
async def update_member(session: AsyncSession, solution: Solution, member_id: UUID, payload: models.AccessUpdate) -> None:
"""Save a reviewed assignment atomically under the Solution management lock."""

await organizations.require_membership(session, member_id, solution.organization_id)
# The caller holds the active Organization lock; only target membership remains to check.
membership = await session.scalar(
select(col(UserOrganization.user_id)).where(
col(UserOrganization.user_id) == member_id, col(UserOrganization.organization_id) == solution.organization_id
)
)
if membership is None:
raise HTTPException(status_code=403, detail="Access required")

# Reject stale catalog reviews before changing assignments.
definition = await catalog(session, solution)
if definition is None or payload.revision_id != solution.deployed_revision_id:
raise HTTPException(status_code=409, detail="Permission catalog changed; reload before saving")
Expand Down
12 changes: 8 additions & 4 deletions api/src/database/services/registries.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from sqlmodel import col
from src.utils import images
from sqlalchemy import select
from sqlalchemy.orm import defer
from sqlalchemy.orm import defer, load_only
from collections.abc import Sequence
from src.models.roles import OrganizationRoles
from src.models.types import Image
Expand Down Expand Up @@ -63,9 +63,13 @@ async def delete(session: AsyncSession, organization_id: UUID, connection_id: UU
await lock(session, organization_id)
await organizations.locked_membership(session, user_id, organization_id, OrganizationRoles.maintain)

# Resolve only registry credentials belonging to the authorized Organization.
connection = await session.get(RegistryConnection, connection_id)
if connection is None or connection.organization_id != organization_id:
# Resolve the tenant-owned identity without decrypting credentials.
connection = await session.scalar(
select(RegistryConnection)
.options(load_only(attr(RegistryConnection.id), raiseload=True))
.where(col(RegistryConnection.id) == connection_id, col(RegistryConnection.organization_id) == organization_id)
)
if connection is None:
raise HTTPException(status_code=404, detail="Registry connection not found")

# Retained deployment revisions must keep their registry credentials available.
Expand Down
55 changes: 20 additions & 35 deletions api/src/kubernetes/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,23 @@ async def dispose_clients() -> None:
connections.push_async_callback(api._session.aclose)


# Keep shared API connections separate from operation-owned tunnels.
class Kubernetes:
"""Borrow one Compute API connection for resource workflows.

Database resources have dedicated Organization namespaces; Solutions run in
the Organization compute namespace. Resource operations borrow this client's
lazy kr8s connection. Database and storage workflows own their tunnel scopes.
"""

def __init__(self, kubeconfig: dict[str, object]) -> None:
"""Initialize one lazy cluster connection."""

self._kubeconfig = kubeconfig

async def api(self) -> Api:
"""Return the cached kr8s client for the configured cluster."""

# Lazily borrow the loop-local connection from kr8s rather than caching it in this wrapper.
api = await kr8s.asyncio.api(kubeconfig=cast(str, self._kubeconfig), serviceaccount="")

# Only the Platform lifespan owns the borrowed transport.
_api_clients.setdefault(asyncio.get_running_loop(), set()).add(api)
return api

async def cluster_uid(self) -> str:
"""Return the stable UID of the configured Kubernetes cluster."""

# The system Namespace is created with the cluster and provides an identity independent of kubeconfig aliases.
system = Namespace("kube-system", api=await self.api())
await system.refresh()
metadata = system.raw.get("metadata")
uid = metadata.get("uid") if isinstance(metadata, dict) else None
if not isinstance(uid, str) or not uid:
raise RuntimeError("Kubernetes cluster identity is unavailable")
return uid
async def api(kubeconfig: dict[str, object]) -> Api:
"""Borrow the loop-local kr8s client owned by the Platform lifespan."""

# kr8s caches clients by configuration and event loop.
connection = await kr8s.asyncio.api(kubeconfig=cast(str, kubeconfig), serviceaccount="")
_api_clients.setdefault(asyncio.get_running_loop(), set()).add(connection)
return connection


async def cluster_uid(api: Api) -> str:
"""Return the stable UID of the configured Kubernetes cluster."""

# The system Namespace provides an identity independent of kubeconfig aliases.
system = Namespace("kube-system", api=api)
await system.refresh()
metadata = system.raw.get("metadata")
uid = metadata.get("uid") if isinstance(metadata, dict) else None
if not isinstance(uid, str) or not uid:
raise RuntimeError("Kubernetes cluster identity is unavailable")
return uid
35 changes: 11 additions & 24 deletions api/src/kubernetes/databases.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from src.database.models.organizations import Organization

if TYPE_CHECKING:
from src.kubernetes.client import Kubernetes
from kr8s.asyncio import Api

ClusterResource = new_class("Cluster", "postgresql.cnpg.io/v1", asyncio=True, plural="clusters")

Expand All @@ -36,22 +36,15 @@ def _allocation(storage_bytes: int, cpu_millicores: int, ram_bytes: int) -> tupl


async def apply(
client: "Kubernetes",
organization_id: UUID,
password: str,
storage_class: str,
*,
storage_bytes: int,
cpu_millicores: int,
ram_bytes: int,
api: "Api", organization_id: UUID, password: str, storage_class: str, *, storage_bytes: int, cpu_millicores: int, ram_bytes: int
) -> None:
"""Create the database boundary and submit the PostgreSQL cluster."""

# Render the isolated database boundary before accessing Kubernetes.
if min(storage_bytes, cpu_millicores, ram_bytes) <= 0:
raise ValueError("Database storage, CPU and RAM capacity must be positive")
database_namespace = namespace.database(organization_id)
existing = ClusterResource("database", namespace=database_namespace, api=await client.api())
existing = ClusterResource("database", namespace=database_namespace, api=api)
try:
await existing.refresh()
except NotFoundError:
Expand All @@ -74,7 +67,6 @@ async def apply(
quota=json.dumps({"pods": "3", "persistentvolumeclaims": "2", **quota}),
resources=json.dumps(resources),
)
api = await client.api()

# Establish independent database quota and ingress before CNPG creates any Pods.
cluster_document = next(document for document in documents if document.get("kind") == "Cluster")
Expand All @@ -99,13 +91,12 @@ async def apply(
await utils.apply(cluster)


async def resize(client: "Kubernetes", organization_id: UUID, *, storage_bytes: int, cpu_millicores: int, ram_bytes: int) -> None:
async def resize(api: "Api", organization_id: UUID, *, storage_bytes: int, cpu_millicores: int, ram_bytes: int) -> None:
"""Reconcile running database resources without shrinking persistent storage."""

# Reject unsafe PVC shrink before mutating any quota or database configuration.
if min(storage_bytes, cpu_millicores, ram_bytes) <= 0:
raise ValueError("Database storage, CPU and RAM capacity must be positive")
api = await client.api()
database_namespace = namespace.database(organization_id)
cluster = ClusterResource("database", namespace=database_namespace, api=api)
await cluster.refresh()
Expand All @@ -119,21 +110,19 @@ async def resize(client: "Kubernetes", organization_id: UUID, *, storage_bytes:
await cluster.patch({"spec": {"storage": {"size": str(storage_bytes)}, "resources": resources}})


async def provisioned_storage_bytes(client: "Kubernetes", organization_id: UUID) -> int:
async def provisioned_storage_bytes(api: "Api", organization_id: UUID) -> int:
"""Read the current persistent allocation before accepting a capacity update."""

# Preserve historic binary allocations exactly when validating decimal-byte requests.
api = await client.api()
cluster = ClusterResource("database", namespace=namespace.database(organization_id), api=api)
await cluster.refresh()
return int(utils.quantity(cluster.spec["storage"]["size"]))


async def wait_ready(client: "Kubernetes", organization_id: UUID) -> None:
async def wait_ready(api: "Api", organization_id: UUID) -> None:
"""Wait for cluster readiness and the expected ready, nonterminating database Pods."""

# Observe readiness without changing externally managed hibernation.
api = await client.api()
database_namespace = namespace.database(organization_id)
cluster = ClusterResource("database", namespace=database_namespace, api=api)
async with asyncio.timeout(2 * 60):
Expand Down Expand Up @@ -194,18 +183,16 @@ async def wait_ready(client: "Kubernetes", organization_id: UUID) -> None:


@asynccontextmanager
async def connection(
organization: Organization, cluster: "Kubernetes", *, certificate: str | None = None
) -> AsyncGenerator[postgres.Postgres]:
async def connection(organization: Organization, api: "Api", *, certificate: str | None = None) -> AsyncGenerator[postgres.Postgres]:
"""Own a private PostgreSQL tunnel using the caller's CA snapshot or a fresh cluster lookup."""

# Refresh the selector before kr8s resolves a ready Pod for the private database tunnel.
service = Service("database-rw", namespace=namespace.database(organization.id), api=await cluster.api())
service = Service("database-rw", namespace=namespace.database(organization.id), api=api)
await service.refresh()
async with service.portforward(5432, local_port="auto") as port:
# Preserve the cluster DNS hostname for certificate verification even through a local tunnel.
if certificate is None:
certificate = await databases.certificate(cluster, organization.id)
certificate = await databases.certificate(api, organization.id)
database = postgres.Postgres(
host=namespace.database_hostname(organization.id),
port=port,
Expand All @@ -218,8 +205,8 @@ async def connection(
yield database


async def certificate(client: "Kubernetes", organization_id: UUID) -> str:
async def certificate(api: "Api", organization_id: UUID) -> str:
"""Read the CNPG-generated server CA as PEM text, not a filesystem path."""

# CNPG's default server CA Secret is named after its Cluster.
return await tls.certificate(client, namespace.database(organization_id), "database-ca", entry="ca.crt")
return await tls.certificate(api, namespace.database(organization_id), "database-ca", entry="ca.crt")
6 changes: 2 additions & 4 deletions api/src/kubernetes/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from kr8s.asyncio.objects import ConfigMap, Deployment

if TYPE_CHECKING:
from src.kubernetes.client import Kubernetes
from kr8s.asyncio import Api


def _deployment_is_ready(deployment: Deployment) -> bool:
Expand All @@ -28,12 +28,11 @@ def _deployment_is_ready(deployment: Deployment) -> bool:
)


async def verify(client: "Kubernetes", gateway_url: str, gateway_certificate: str | None = None) -> None:
async def verify(api: "Api", gateway_url: str, gateway_certificate: str | None = None) -> None:
"""Inspect package compatibility and readiness without changing infrastructure."""

# Configure trust before opening the operator-configured endpoint.
context = ssl.create_default_context(cadata=gateway_certificate)
api = await client.api()

# The deployment owner applies the release contract only after shared infrastructure.
release = ConfigMap("compute-release", namespace="longlink-system", api=api)
Expand Down Expand Up @@ -63,7 +62,6 @@ async def verify(client: "Kubernetes", gateway_url: str, gateway_certificate: st
http_client = httpx2.AsyncClient(verify=context, trust_env=False, timeout=10, follow_redirects=False)
async with http_client:
while True:

# Probe routing only after the deployment checks succeed.
try:
response = await http_client.get(f"{gateway_url.rstrip('/')}/ready", headers={"Host": "internalkourier"})
Expand Down
5 changes: 2 additions & 3 deletions api/src/kubernetes/organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from src.models.organizations import MAX_SOLUTIONS, MAX_SOLUTION_CPU_MILLICORES

if TYPE_CHECKING:
from src.kubernetes.client import Kubernetes
from kr8s.asyncio import Api


async def apply(client: "Kubernetes", organization_id: UUID, *, cpu_millicores: int, ram_bytes: int) -> None:
async def apply(api: "Api", organization_id: UUID, *, cpu_millicores: int, ram_bytes: int) -> None:
"""Create one Organization Namespace boundary for its explicit lifecycle."""

# Render and apply only the requested Organization boundary.
Expand All @@ -33,7 +33,6 @@ async def apply(client: "Kubernetes", organization_id: UUID, *, cpu_millicores:
)

# Apply the Namespace before its policy through the lifecycle owner's connection.
api = await client.api()
compute_boundary = Namespace(namespace_manifest, api=api)
await utils.apply(compute_boundary)

Expand Down
15 changes: 4 additions & 11 deletions api/src/kubernetes/solutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@
import asyncio
from kr8s import ServerError, NotFoundError, APITimeoutError, ConnectionClosedError
from uuid import UUID
from typing import TYPE_CHECKING, cast
from typing import cast
from src.utils import templates
from kr8s.asyncio import Api
from src.kubernetes import utils, namespace
from collections.abc import AsyncIterator
from importlib.resources import files
from kr8s.asyncio.objects import Job, Pod, Secret, APIObject, Namespace, new_class

if TYPE_CHECKING:
from src.kubernetes.client import Kubernetes

SOLUTION_ID_LABEL = "longlink.io/solution-id"
KnativeServiceResource = new_class("Service", "serving.knative.dev/v1", asyncio=True, plural="services")

Expand Down Expand Up @@ -152,7 +149,7 @@ async def _wait_for_rollout(deployed: APIObject) -> None:


async def apply(
client: "Kubernetes",
api: "Api",
organization_id: UUID,
solution_id: UUID,
image: str,
Expand Down Expand Up @@ -184,8 +181,6 @@ async def apply(
pull_secrets=json.dumps([{"name": f"registry-{registry_connection_id}"}] if registry_connection_id is not None else []),
)

api = await client.api()

# Stop interrupted migrations before another release or fallback can use the schema.
await _stop_migrations(api, compute_namespace, solution_id, resume_job=migration_id if migrate else None)

Expand Down Expand Up @@ -215,12 +210,11 @@ async def apply(
await _wait_for_rollout(deployed)


async def delete(client: "Kubernetes", organization_id: UUID, solution_id: UUID) -> None:
async def delete(api: "Api", organization_id: UUID, solution_id: UUID) -> None:
"""Delete one Solution and wait until its Pods have terminated."""

# Recheck only Kubernetes state while resources and Pods terminate.
compute_namespace = namespace.compute(organization_id)
api = await client.api()
namespace_resource = Namespace(compute_namespace, api=api)
while await namespace_resource.exists():
remaining = False
Expand All @@ -241,13 +235,12 @@ async def delete(client: "Kubernetes", organization_id: UUID, solution_id: UUID)
await asyncio.sleep(5)


async def logs(client: "Kubernetes", organization_id: UUID, solution_id: UUID) -> list[str]:
async def logs(api: "Api", organization_id: UUID, solution_id: UUID) -> list[str]:
"""Return recent logs for one managed Solution Pod."""

# Scope the Solution Pod lookup to its Organization Namespace.
try:
compute_namespace = namespace.compute(organization_id)
api = await client.api()
migration_pod: Pod | None = None
async for candidate in Pod.list(api=api, namespace=compute_namespace, label_selector={SOLUTION_ID_LABEL: str(solution_id)}):
pod = cast(Pod, candidate)
Expand Down
Loading