From b977b92d371efa5af104fec0293117412838bb56 Mon Sep 17 00:00:00 2001 From: Jvst Me Date: Wed, 25 Nov 2026 20:40:37 +0100 Subject: [PATCH] Updating gateway OpenTelemetry settings in-place The `otel` gateway configuration property can now be updated in-place, without re-creating the gateway. ```shell $ dstack apply -f gateway.dstack.yml Found gateway my-gateway. Detected changes that can be updated in-place: - otel Update the gateway? [y/n]: ``` `dstack` resubmits the config to the gateway when it detects a change, as part of the state sync mechanism. The gateway app restarts to apply the new OpenTelemetry settings. --- src/dstack/_internal/core/models/gateways.py | 7 +- src/dstack/_internal/proxy/gateway/app.py | 2 + src/dstack/_internal/proxy/gateway/models.py | 2 + .../_internal/proxy/gateway/routers/config.py | 1 + .../proxy/gateway/routers/services.py | 4 +- .../_internal/proxy/gateway/routers/state.py | 19 + .../_internal/proxy/gateway/schemas/config.py | 1 + .../_internal/proxy/gateway/schemas/state.py | 12 + .../pipeline_tasks/gateway_replicas.py | 82 ++-- .../server/services/gateways/__init__.py | 121 ++--- .../server/services/gateways/client.py | 33 +- .../proxy/gateway/routers/test_config.py | 5 +- .../proxy/gateway/routers/test_state.py | 35 ++ .../pipeline_tasks/test_gateway_replicas.py | 463 +++++++++++++----- .../_internal/server/routers/test_gateways.py | 46 -- .../server/services/gateways/test_gateways.py | 71 +-- 16 files changed, 545 insertions(+), 359 deletions(-) create mode 100644 src/dstack/_internal/proxy/gateway/routers/state.py create mode 100644 src/dstack/_internal/proxy/gateway/schemas/state.py create mode 100644 src/tests/_internal/proxy/gateway/routers/test_state.py diff --git a/src/dstack/_internal/core/models/gateways.py b/src/dstack/_internal/core/models/gateways.py index af16a03ce8..f2f07f57d8 100644 --- a/src/dstack/_internal/core/models/gateways.py +++ b/src/dstack/_internal/core/models/gateways.py @@ -214,7 +214,12 @@ class GatewayConfiguration(CoreModel): ] = None otel: Annotated[ Optional[GatewayOTelConfig], - Field(description=("The OpenTelemetry export configuration of the gateway app")), + Field( + description=( + "The OpenTelemetry export configuration of the gateway app." + " Can be updated in-place" + ) + ), ] = None _validate_tags = field_validator("tags", mode="before")(tags_validator) diff --git a/src/dstack/_internal/proxy/gateway/app.py b/src/dstack/_internal/proxy/gateway/app.py index 33722626cf..3b5090997e 100644 --- a/src/dstack/_internal/proxy/gateway/app.py +++ b/src/dstack/_internal/proxy/gateway/app.py @@ -26,6 +26,7 @@ from dstack._internal.proxy.gateway.routers.metering import router as metering_router from dstack._internal.proxy.gateway.routers.registry import router as registry_router from dstack._internal.proxy.gateway.routers.services import router as services_router +from dstack._internal.proxy.gateway.routers.state import router as state_router from dstack._internal.proxy.gateway.routers.stats import router as stats_router from dstack._internal.proxy.gateway.services.metering import FLUSH_INTERVAL, GatewayProxyMeter from dstack._internal.proxy.gateway.services.nginx import Nginx @@ -117,6 +118,7 @@ def make_app( app.include_router(model_proxy_router, prefix="/api/models") app.include_router(registry_router, prefix="/api/registry") app.include_router(services_router, prefix="/api/services") + app.include_router(state_router, prefix="/api/state") app.include_router(stats_router, prefix="/api/stats") @app.get("/") diff --git a/src/dstack/_internal/proxy/gateway/models.py b/src/dstack/_internal/proxy/gateway/models.py index 234b042b1b..385d0593d6 100644 --- a/src/dstack/_internal/proxy/gateway/models.py +++ b/src/dstack/_internal/proxy/gateway/models.py @@ -51,3 +51,5 @@ def any_enabled(self) -> bool: class GlobalProxyConfig(ImmutableModel): acme_settings: ACMESettings = ACMESettings() otel_settings: Optional[OTelSettings] = None + config_hash: Optional[str] = None + """Computed by the server. Reported back to detect outdated config""" diff --git a/src/dstack/_internal/proxy/gateway/routers/config.py b/src/dstack/_internal/proxy/gateway/routers/config.py index 25b5862c4f..3b8cfca0e8 100644 --- a/src/dstack/_internal/proxy/gateway/routers/config.py +++ b/src/dstack/_internal/proxy/gateway/routers/config.py @@ -28,6 +28,7 @@ async def update_global_config( eab_hmac_key=body.acme_eab_hmac_key, ), otel_settings=body.otel_settings, + config_hash=body.config_hash, ), ) if otel.apply_settings(body.otel_settings): diff --git a/src/dstack/_internal/proxy/gateway/routers/services.py b/src/dstack/_internal/proxy/gateway/routers/services.py index b1ad11fcdf..cf8c438aa1 100644 --- a/src/dstack/_internal/proxy/gateway/routers/services.py +++ b/src/dstack/_internal/proxy/gateway/routers/services.py @@ -10,8 +10,10 @@ router = APIRouter() -@router.get("/list") +@router.get("/list", deprecated=True) async def list_all_services( repo: Annotated[GatewayProxyRepo, Depends(get_gateway_proxy_repo)], ) -> ServiceListResponse: + """Deprecated in favor of `/api/state/get_summary`.""" + # TODO: drop when most users upgrade to 0.22.9+ return await list_services(repo) diff --git a/src/dstack/_internal/proxy/gateway/routers/state.py b/src/dstack/_internal/proxy/gateway/routers/state.py new file mode 100644 index 0000000000..2a0b875c20 --- /dev/null +++ b/src/dstack/_internal/proxy/gateway/routers/state.py @@ -0,0 +1,19 @@ +from typing import Annotated + +from fastapi import APIRouter, Depends + +from dstack._internal.proxy.gateway.deps import get_gateway_proxy_repo +from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.schemas.state import StateSummaryResponse +from dstack._internal.proxy.gateway.services.services import list_services + +router = APIRouter() + + +@router.get("/get_summary") +async def get_state_summary( + repo: Annotated[GatewayProxyRepo, Depends(get_gateway_proxy_repo)], +) -> StateSummaryResponse: + services = await list_services(repo) + config = await repo.get_config() + return StateSummaryResponse(services=services.services, config_hash=config.config_hash) diff --git a/src/dstack/_internal/proxy/gateway/schemas/config.py b/src/dstack/_internal/proxy/gateway/schemas/config.py index 85b67c32f9..6f686cd672 100644 --- a/src/dstack/_internal/proxy/gateway/schemas/config.py +++ b/src/dstack/_internal/proxy/gateway/schemas/config.py @@ -10,3 +10,4 @@ class ConfigRequest(BaseModel): acme_eab_kid: Optional[str] = None acme_eab_hmac_key: Optional[str] = None otel_settings: Optional[OTelSettings] = None + config_hash: Optional[str] = None diff --git a/src/dstack/_internal/proxy/gateway/schemas/state.py b/src/dstack/_internal/proxy/gateway/schemas/state.py new file mode 100644 index 0000000000..86d582d496 --- /dev/null +++ b/src/dstack/_internal/proxy/gateway/schemas/state.py @@ -0,0 +1,12 @@ +from typing import Optional + +from dstack._internal.core.models.common import CoreModel +from dstack._internal.proxy.gateway.schemas.services import ServiceListItem + + +class StateSummaryResponse(CoreModel): + """The model is minimal to allow for frequent polling by the server""" + + services: list[ServiceListItem] + config_hash: Optional[str] = None + """The hash sent by the server along with the current config""" diff --git a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py index 9c0a265177..aabb244ce9 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py @@ -539,7 +539,6 @@ async def _process_provisioning_item(item: GatewayReplicaPipelineItem): GatewayReplicaModel.instance_id, GatewayReplicaModel.backend_id, GatewayReplicaModel.configuration, - GatewayReplicaModel.region, ], gateway_fields=_GATEWAY_FIELDS_MIN + [ @@ -550,7 +549,6 @@ async def _process_provisioning_item(item: GatewayReplicaPipelineItem): GatewayModel.backend_data, ], load_backends=True, - load_gateway_project=True, load_gateway_backend_type=True, ) if replica_model is None: @@ -565,7 +563,7 @@ async def _process_provisioning_item(item: GatewayReplicaPipelineItem): if _is_legacy_aws_acm_gateway_with_pending_migration(gateway_model): await _commit_update(item, replica_model, update_map={}) return - error = await _connect_and_configure_gateway_replica(gateway_model, replica_model) + error = await _connect_to_gateway_replica(replica_model) if error is not None: await _commit_update( item, @@ -629,14 +627,11 @@ async def _register_replica_with_load_balancer( return None -async def _connect_and_configure_gateway_replica( - gateway_model: GatewayModel, - gateway_replica: GatewayReplicaModel, -) -> Optional[str]: +async def _connect_to_gateway_replica(gateway_replica: GatewayReplicaModel) -> Optional[str]: """Returns an error message on failure, None on success.""" logger.debug("%s: connecting to gateway replica", fmt(gateway_replica)) # TODO: do only one connection/configuration attempt per pipeline tick. - # Blocking on connect_to_gateway_replica_with_retry and configure_gateway_replica now has + # Blocking on connect_to_gateway_replica_with_retry and wait_for_gateway_replica_app now has # these cons: # - cannot terminate the gateway replica before it is provisioned because the DB model is locked # - connection retry counter is reset on server restart @@ -645,15 +640,11 @@ async def _connect_and_configure_gateway_replica( if connection is None: return "Failed to connect to gateway replica" try: - async with get_session_ctx() as session: - otel_settings = await gateways_services.resolve_gateway_replica_otel_settings( - session, gateway_model, gateway_replica - ) - await gateways_services.configure_gateway_replica(connection, otel_settings) + await gateways_services.wait_for_gateway_replica_app(connection) except Exception: - logger.exception("%s: failed to configure gateway replica", fmt(gateway_replica)) - return "Failed to configure gateway replica" - logger.info("%s: gateway replica connected and configured", fmt(gateway_replica)) + logger.exception("%s: gateway replica app is not available", fmt(gateway_replica)) + return "Gateway replica app is not available" + logger.info("%s: gateway replica connected", fmt(gateway_replica)) return None @@ -696,7 +687,11 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): return async with connection.client() as client: try: - currently_registered_services = await client.list_services() + state_summary = await client.get_state_summary() + if state_summary is not None: + currently_registered_services = state_summary.services + else: + currently_registered_services = await client.list_services() except Exception as e: if isinstance(e, HTTPStatusError) and e.response.status_code == 404: logger.warning( @@ -707,7 +702,7 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): fmt(replica_model), ) else: - logger.warning("%s: failed to list services: %r", fmt(replica_model), e) + logger.warning("%s: failed to get gateway state: %r", fmt(replica_model), e) await _commit_update(item, replica_model, update_map={}) return # Imports are synced only where exports are enabled. @@ -715,6 +710,22 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): if are_exports_enabled(): currently_registered_imports = await _list_imports(client, replica_model) await _run_process_running_gateway_replica_hooks(replica_model, connection) + if state_summary is not None: + try: + config_submitted = await _sync_gateway_config( + connection, gateway_model, replica_model, state_summary.config_hash + ) + except Exception as e: + logger.warning("%s: failed to submit gateway config: %r", fmt(replica_model), e) + # Do not attempt service registration in this pipeline tick - we failed to submit the + # config, so the gateway may attempt to request certificates from the wrong ACME server + await _commit_update(item, replica_model, update_map={}) + return + if config_submitted and state_summary.config_hash is not None: + # Do nothing else in this pipeline tick - the gateway app may be temporarily down + # if the OTel config has changed. + await _commit_update(item, replica_model, update_map={}) + return run_filters = (RunModel.gateway_id == gateway_model.id, *get_running_service_filters()) job_filters = (JobModel.status == JobStatus.RUNNING, JobModel.registered == True) run_fields: list[InstrumentedAttribute[Any]] = [RunModel.id] @@ -775,22 +786,6 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): session, plan ) - if plan.register_services: - # Registering a service may request a TLS certificate. A reinstalled gateway has - # lost its global config along with its services, and certbot would fall back to - # its default ACME server, so resend the config first. - try: - async with get_session_ctx() as session: - otel_settings = await gateways_services.resolve_gateway_replica_otel_settings( - session, gateway_model, replica_model - ) - async with connection.client() as client: - await client.submit_gateway_config(otel_settings) - except Exception as e: - logger.warning("%s: failed to submit gateway config: %r", fmt(replica_model), e) - await _commit_update(item, replica_model, update_map={}) - return - sync_result = await _perform_state_sync( connection, gateway_model, replica_model, run_models_by_id, job_models_by_id, plan ) @@ -919,6 +914,25 @@ async def _get_expected_imports( return set(imports.values()) +async def _sync_gateway_config( + connection: GatewayConnection, + gateway_model: GatewayModel, + replica_model: GatewayReplicaModel, + current_config_hash: Optional[str], +) -> bool: + async with get_session_ctx() as session: + config = await gateways_services.get_gateway_replica_config( + session, gateway_model, replica_model + ) + if config.config_hash == current_config_hash: + return False + logger.debug("%s: submitting gateway config", fmt(replica_model)) + async with connection.client() as client: + await client.submit_gateway_config(config) + logger.info("%s: gateway config submitted", fmt(replica_model)) + return True + + async def _perform_state_sync( connection: GatewayConnection, gateway_model: GatewayModel, diff --git a/src/dstack/_internal/server/services/gateways/__init__.py b/src/dstack/_internal/server/services/gateways/__init__.py index 07ccb96ba3..0e6db3bf8d 100644 --- a/src/dstack/_internal/server/services/gateways/__init__.py +++ b/src/dstack/_internal/server/services/gateways/__init__.py @@ -1,8 +1,11 @@ import asyncio import datetime +import hashlib +import hmac import itertools +import json import uuid -from collections.abc import AsyncGenerator, Mapping +from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from datetime import timedelta from typing import List, Optional, Sequence @@ -53,6 +56,7 @@ from dstack._internal.core.services.gateways import diff_gateway_configurations from dstack._internal.proxy.gateway.const import SERVICE_SCALING_WINDOWS from dstack._internal.proxy.gateway.models import OTelSettings +from dstack._internal.proxy.gateway.schemas.config import ConfigRequest from dstack._internal.proxy.gateway.schemas.stats import PerWindowStats, Stat from dstack._internal.server import settings from dstack._internal.server.db import get_db, is_db_postgres, is_db_sqlite @@ -98,7 +102,7 @@ from dstack._internal.utils.logging import get_logger logger = get_logger(__name__) -_CONF_UPDATABLE_FIELDS = frozenset({"domain", "default", "replicas"}) +_CONF_UPDATABLE_FIELDS = frozenset({"domain", "default", "replicas", "otel"}) def switch_gateway_status( @@ -167,8 +171,8 @@ def emit_gateway_replica_status_change_event( GATEWAY_CONNECT_ATTEMPTS = 30 GATEWAY_CONNECT_DELAY = 10 -GATEWAY_CONFIGURE_ATTEMPTS = 50 -GATEWAY_CONFIGURE_DELAY = 3 +GATEWAY_APP_START_ATTEMPTS = 50 +GATEWAY_APP_START_DELAY = 3 async def list_project_gateways( @@ -756,46 +760,13 @@ def _merge_per_window_stats(stats_per_gateway_replica: list[PerWindowStats]) -> async def init_gateways(session: AsyncSession): res = await session.execute( - select(GatewayReplicaModel) - .where( + select(GatewayReplicaModel).where( GatewayReplicaModel.status == GatewayReplicaStatus.RUNNING, GatewayReplicaModel.active == True, GatewayReplicaModel.deleted == False, ) - .options( - *( - joinedload(gateway_attr).options( - joinedload(GatewayModel.project), - joinedload(GatewayModel.backend).load_only(BackendModel.type), - ) - for gateway_attr in ( - GatewayReplicaModel.gateway, - GatewayReplicaModel.legacy_gateway, - ) - ) - ) ) - gateway_replicas = res.unique().scalars().all() - otel_settings: dict[str, Optional[OTelSettings]] = {} - secrets_cache: dict[uuid.UUID, Mapping[str, str]] = {} - for gateway_replica in gateway_replicas: - if gateway_replica.ip_address is None: - continue - try: - replica_otel_settings = await resolve_gateway_replica_otel_settings( - session, - gateway_replica.gateway or gateway_replica.legacy_gateway, - gateway_replica, - secrets_cache=secrets_cache, - ) - except Exception: - # Don't let one gateway prevent initializing the others - logger.exception( - "Failed to resolve OpenTelemetry settings for gateway replica %s", - gateway_replica.ip_address, - ) - replica_otel_settings = None - otel_settings[gateway_replica.ip_address] = replica_otel_settings + gateway_replicas = res.scalars().all() if len(gateway_replicas) > 0: logger.info( @@ -840,17 +811,6 @@ async def init_gateways(session: AsyncSession): elif isinstance(res, bool) and res: gateway_replica.app_updated_at = get_current_datetime() - for connection, error in await gather_map_async( - [c for c in await gateway_connections_pool.all() if c.ip_address in otel_settings], - # Need several attempts to handle short gateway replica downtime after update - lambda c: configure_gateway_replica(c, otel_settings[c.ip_address], attempts=7), - return_exceptions=True, - ): - if isinstance(error, Exception): - logger.warning( - "Failed to configure gateway replica %s: %r", connection.ip_address, error - ) - _GATEWAY_UPDATE_TIMEOUT = 600 @@ -889,63 +849,74 @@ def _recently_updated(gateway_replica_model: GatewayReplicaModel) -> bool: ) > get_current_datetime() - timedelta(seconds=60) -async def configure_gateway_replica( +async def wait_for_gateway_replica_app( connection: GatewayConnection, - otel_settings: Optional[OTelSettings], - attempts: int = GATEWAY_CONFIGURE_ATTEMPTS, + attempts: int = GATEWAY_APP_START_ATTEMPTS, ) -> None: - """ - Try submitting gateway config to the replica several times in case its HTTP server is not - running yet - """ - - logger.debug("Configuring gateway replica %s", connection.ip_address) + logger.debug("Waiting for gateway replica %s app", connection.ip_address) for attempt in range(attempts - 1): try: async with connection.client() as client: - await client.submit_gateway_config(otel_settings) + await client.info() break except httpx.RequestError as e: logger.debug( - "Failed attempt %s/%s at configuring gateway replica %s: %r", + "(attempt %s/%s) Gateway replica %s not yet available: %r", attempt + 1, attempts, connection.ip_address, e, ) - await asyncio.sleep(GATEWAY_CONFIGURE_DELAY) + await asyncio.sleep(GATEWAY_APP_START_DELAY) else: async with connection.client() as client: - await client.submit_gateway_config(otel_settings) + await client.info() + + logger.info("Gateway replica %s is available", connection.ip_address) - logger.info("Gateway replica %s configured", connection.ip_address) + +async def get_gateway_replica_config( + session: AsyncSession, gateway_model: GatewayModel, replica_model: GatewayReplicaModel +) -> ConfigRequest: + """The result contains secret values""" + otel_settings = await resolve_gateway_replica_otel_settings( + session, gateway_model, replica_model + ) + return build_gateway_config(otel_settings, hash_key=replica_model.ssh_private_key) async def resolve_gateway_replica_otel_settings( session: AsyncSession, gateway_model: Optional[GatewayModel], replica_model: GatewayReplicaModel, - secrets_cache: Optional[dict[uuid.UUID, Mapping[str, str]]] = None, ) -> Optional[OTelSettings]: - """ - `secrets_cache` maps project IDs to project secrets. When resolving settings - for many replicas, pass the same dict to fetch each project's secrets only once. - """ if gateway_model is None: return None configuration = get_gateway_configuration(gateway_model) if configuration.otel is None or not is_gateway_otel_enabled(configuration.otel): return None - if secrets_cache is None: - secrets_cache = {} - secrets = secrets_cache.get(gateway_model.project_id) - if secrets is None: - secrets = await get_project_secrets_mapping(session=session, project=gateway_model.project) - secrets_cache[gateway_model.project_id] = secrets + secrets = await get_project_secrets_mapping(session=session, project=gateway_model.project) return get_gateway_replica_otel_settings(gateway_model, configuration, replica_model, secrets) +def build_gateway_config(otel_settings: Optional[OTelSettings], hash_key: str) -> ConfigRequest: + config = ConfigRequest.model_validate( + { + "acme_server": settings.ACME_SERVER, + "acme_eab_kid": settings.ACME_EAB_KID, + "acme_eab_hmac_key": settings.ACME_EAB_HMAC_KEY, + "otel_settings": otel_settings, + } + ) + # None is excluded, so that adding new optional settings in new dstack versions + # does not change existing hashes + payload = json.dumps(config.model_dump(mode="json", exclude_none=True), sort_keys=True) + # HMAC, so that the hash cannot be used to guess secret values + config_hash = hmac.new(hash_key.encode(), payload.encode(), hashlib.sha256).hexdigest() + return config.model_copy(update={"config_hash": config_hash}) + + def get_gateway_replica_models(gateway_model: GatewayModel) -> List[GatewayReplicaModel]: replicas = list(gateway_model.gateway_replicas) if gateway_model.gateway_replica is not None: # pre-0.20.25 gateway diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index 8642a3765b..799591c83a 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -11,7 +11,7 @@ from dstack._internal.core.models.configurations import RateLimit, ServiceConfiguration from dstack._internal.core.models.instances import SSHConnectionParams from dstack._internal.core.models.runs import JobSpec, JobSubmission, get_service_port -from dstack._internal.proxy.gateway.models import OTelSettings +from dstack._internal.proxy.gateway.schemas.config import ConfigRequest from dstack._internal.proxy.gateway.schemas.metering import ( CollectMeteringRequest, CollectMeteringResponse, @@ -26,8 +26,8 @@ UpdateReplicaProxyJumpKeysResponse, ) from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListResponse +from dstack._internal.proxy.gateway.schemas.state import StateSummaryResponse from dstack._internal.proxy.gateway.schemas.stats import ServiceStats -from dstack._internal.server import settings class GatewayClient: @@ -38,7 +38,7 @@ def __init__(self, uds: Optional[str] = None, port: Optional[int] = None): raise ValueError("Either uds or port should be specified, not both") # Shows that the gateway's HTTP server has started. Should become True - # in submit_gateway_config during gateway setup. If setup fails, it + # in info() during gateway setup. If setup fails, it # should become True after any other successful request. self.is_server_ready = False @@ -239,6 +239,8 @@ async def list_imports(self) -> list[ImportListItem]: return validate_json_extra_ignore(ImportListResponse, resp.content).imports async def list_services(self) -> list[ServiceListItem]: + """Deprecated in favor of `get_state_summary`.""" + # TODO: drop when most users upgrade to 0.22.9+ resp = await self._client.get(self._url("/api/services/list")) if resp.status_code == 400: raise gateway_error(resp.json()) @@ -247,17 +249,22 @@ async def list_services(self) -> list[ServiceListItem]: self.is_server_ready = True return resp_parsed.services - async def submit_gateway_config(self, otel_settings: Optional[OTelSettings]) -> None: + async def get_state_summary(self) -> Optional[StateSummaryResponse]: + resp = await self._client.get(self._url("/api/state/get_summary")) + if resp.status_code == 404: + # An older gateway not yet updated to 0.22.9+ + # TODO: drop when most users upgrade to 0.22.9+ + return None + if resp.status_code == 400: + raise gateway_error(resp.json()) + resp.raise_for_status() + resp_parsed = validate_json_extra_ignore(StateSummaryResponse, resp.content) + self.is_server_ready = True + return resp_parsed + + async def submit_gateway_config(self, config: ConfigRequest) -> None: resp = await self._client.post( - self._url("/api/config"), - json={ - "acme_server": settings.ACME_SERVER, - "acme_eab_kid": settings.ACME_EAB_KID, - "acme_eab_hmac_key": settings.ACME_EAB_HMAC_KEY, - "otel_settings": ( - otel_settings.model_dump(mode="json") if otel_settings is not None else None - ), - }, + self._url("/api/config"), json=config.model_dump(mode="json") ) if resp.status_code == 400: raise gateway_error(resp.json()) diff --git a/src/tests/_internal/proxy/gateway/routers/test_config.py b/src/tests/_internal/proxy/gateway/routers/test_config.py index e247d36b44..036489878e 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_config.py +++ b/src/tests/_internal/proxy/gateway/routers/test_config.py @@ -38,11 +38,14 @@ async def test_saves_and_applies_otel_settings( } async with make_client(repo) as client: - resp = await client.post("/api/config", json={"otel_settings": otel_settings}) + resp = await client.post( + "/api/config", json={"otel_settings": otel_settings, "config_hash": "hash"} + ) assert resp.status_code == 200 expected = OTelSettings(**otel_settings) assert (await repo.get_config()).otel_settings == expected + assert (await repo.get_config()).config_hash == "hash" apply_settings.assert_called_once_with(expected) if restart_required: kill.assert_called_once() diff --git a/src/tests/_internal/proxy/gateway/routers/test_state.py b/src/tests/_internal/proxy/gateway/routers/test_state.py new file mode 100644 index 0000000000..71ae1bb3ff --- /dev/null +++ b/src/tests/_internal/proxy/gateway/routers/test_state.py @@ -0,0 +1,35 @@ +import httpx +import pytest + +from dstack._internal.proxy.gateway.app import make_app +from dstack._internal.proxy.gateway.models import GlobalProxyConfig +from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.lib.testing.common import make_project, make_service + + +def make_client(repo: GatewayProxyRepo) -> httpx.AsyncClient: + app = make_app(repo) + return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test/") + + +@pytest.mark.asyncio +class TestGetStateSummary: + async def test_empty(self): + async with make_client(GatewayProxyRepo()) as client: + resp = await client.get("/api/state/get_summary") + + assert resp.status_code == 200 + assert resp.json() == {"services": [], "config_hash": None} + + async def test_returns_services_and_config_hash(self): + repo = GatewayProxyRepo() + await repo.set_project(make_project("test-proj")) + await repo.set_service(make_service("test-proj", "srv-1", run_id="srv-1-id")) + await repo.set_config(GlobalProxyConfig(config_hash="hash")) + + async with make_client(repo) as client: + resp = await client.get("/api/state/get_summary") + + assert resp.status_code == 200 + assert [s["run_name"] for s in resp.json()["services"]] == ["srv-1"] + assert resp.json()["config_hash"] == "hash" diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py index d1f3a82013..470d86bd80 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py @@ -15,6 +15,7 @@ from dstack._internal.core.models.configurations import ServiceConfiguration from dstack._internal.core.models.gateways import ( ACMGatewayCertificate, + GatewayOTelConfig, GatewayReplicaProvisioningData, GatewayReplicaStatus, GatewayStatus, @@ -29,6 +30,7 @@ from dstack._internal.core.models.services import OpenAIChatModel from dstack._internal.proxy.gateway.schemas.registry import ImportListItem from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListReplicaItem +from dstack._internal.proxy.gateway.schemas.state import StateSummaryResponse from dstack._internal.server import settings from dstack._internal.server.background.pipeline_tasks import gateway_replicas from dstack._internal.server.background.pipeline_tasks.gateway_replicas import ( @@ -49,6 +51,10 @@ UserModel, ) from dstack._internal.server.services import exports as exports_service +from dstack._internal.server.services.gateways import ( + build_gateway_config, + get_gateway_configuration, +) from dstack._internal.server.testing.common import ( AsyncContextManager, ComputeMockSpec, @@ -62,6 +68,7 @@ create_project, create_repo, create_run, + create_secret, create_service_run, create_user, get_gateway_replica_configuration, @@ -793,7 +800,9 @@ async def test_calls_hooks_and_processes_replica_if_hook_fails( ) _lock_replica(replica) await session.commit() - _get_client_mock(mock_gateway_connection).list_services.return_value = [] + _get_client_mock( + mock_gateway_connection + ).get_state_summary.return_value = _get_state_summary(replica, []) failing_hook = AsyncMock(side_effect=RuntimeError("hook failed")) hook = AsyncMock() monkeypatch.setattr( @@ -814,6 +823,15 @@ def _get_client_mock(mock_gateway_connection: AsyncMock) -> AsyncMock: return mock_gateway_connection.return_value.client.return_value.__aenter__.return_value +def _get_state_summary( + replica: GatewayReplicaModel, services: list[ServiceListItem], config_synced: bool = True +) -> StateSummaryResponse: + config_hash = None + if config_synced: + config_hash = build_gateway_config(None, hash_key=replica.ssh_private_key).config_hash + return StateSummaryResponse(services=services, config_hash=config_hash) + + @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestGatewayReplicaWorkerRunningStateSync: @@ -884,7 +902,7 @@ async def test_updates_proxy_jump_key_without_unregistering_or_changing_job( replicas=list(reported.values()), ) client = _get_client_mock(mock_gateway_connection) - client.list_services.return_value = [service] + client.get_state_summary.return_value = _get_state_summary(replica, [service]) async def update(updates): if failure == "update": @@ -1009,7 +1027,9 @@ async def test_registers_new_service_and_replica( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, [], config_synced=False + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1106,7 +1126,9 @@ async def test_skips_registration_if_gateway_config_not_submitted( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, [], config_synced=False + ) client_mock.submit_gateway_config.side_effect = RuntimeError("gateway unavailable") await worker.process(_replica_to_pipeline_item(replica)) @@ -1119,6 +1141,151 @@ async def test_skips_registration_if_gateway_config_not_submitted( assert replica.status == GatewayReplicaStatus.RUNNING assert replica.lock_token is None + async def test_resubmits_outdated_config_and_postpones_sync( + self, + test_db, + session: AsyncSession, + worker: GatewayReplicaWorker, + mock_gateway_connection: AsyncMock, + ): + project = await create_project(session=session) + user = await create_user(session=session) + repo = await create_repo(session=session, project_id=project.id) + backend = await create_backend(session=session, project_id=project.id) + gateway = await create_gateway( + session=session, + project_id=project.id, + backend_id=backend.id, + status=GatewayStatus.RUNNING, + ) + replica = await create_gateway_replica( + session=session, + gateway_id=gateway.id, + backend=backend, + status=GatewayReplicaStatus.RUNNING, + ) + await self._create_service_run_and_job( + session, project, repo, user, gateway, run_name="test-service" + ) + _lock_replica(replica) + await session.commit() + + client_mock = _get_client_mock(mock_gateway_connection) + client_mock.get_state_summary.return_value = StateSummaryResponse( + services=[], config_hash="outdated" + ) + + await worker.process(_replica_to_pipeline_item(replica)) + + client_mock.submit_gateway_config.assert_awaited_once() + config = client_mock.submit_gateway_config.await_args.args[0] + assert config.config_hash == _get_state_summary(replica, []).config_hash + # The gateway may be restarting to apply the config + client_mock.register_service.assert_not_called() + await session.refresh(replica) + assert replica.lock_token is None + + async def test_submits_otel_settings( + self, + test_db, + session: AsyncSession, + worker: GatewayReplicaWorker, + mock_gateway_connection: AsyncMock, + ): + project = await create_project(session=session, name="main") + backend = await create_backend(session=session, project_id=project.id) + gateway = await create_gateway( + session=session, + project_id=project.id, + backend_id=backend.id, + name="my-gateway", + status=GatewayStatus.RUNNING, + ) + configuration = get_gateway_configuration(gateway) + configuration.otel = GatewayOTelConfig( + endpoint="https://otlp", + headers={"Authorization": "Bearer ${{ secrets.token }}"}, + traces=True, + ) + gateway.configuration = configuration.model_dump_json() + await create_secret(session=session, project=project, name="token", value="s3cret") + replica = await create_gateway_replica( + session=session, + gateway_id=gateway.id, + backend=backend, + status=GatewayReplicaStatus.RUNNING, + replica_num=1, + ) + _lock_replica(replica) + await session.commit() + + client_mock = _get_client_mock(mock_gateway_connection) + client_mock.get_state_summary.return_value = _get_state_summary( + replica, [], config_synced=False + ) + await worker.process(_replica_to_pipeline_item(replica)) + + client_mock.submit_gateway_config.assert_awaited_once() + config = client_mock.submit_gateway_config.await_args.args[0] + otel_settings = config.otel_settings + assert otel_settings.traces_enabled + assert otel_settings.headers == {"Authorization": "Bearer s3cret"} + attributes = otel_settings.resource_attributes + assert attributes["service.instance.id"] == str(replica.id) + assert attributes["dstack.project.name"] == "main" + assert attributes["dstack.gateway.name"] == "my-gateway" + assert attributes["dstack.backend"] == backend.type.value + + client_mock.reset_mock() + client_mock.get_state_summary.return_value = StateSummaryResponse( + services=[], config_hash=config.config_hash + ) + await session.refresh(replica) + _lock_replica(replica) + await session.commit() + await worker.process(_replica_to_pipeline_item(replica)) + + client_mock.submit_gateway_config.assert_not_called() + + async def test_skips_config_sync_for_older_gateways( + self, + test_db, + session: AsyncSession, + worker: GatewayReplicaWorker, + mock_gateway_connection: AsyncMock, + ): + project = await create_project(session=session) + user = await create_user(session=session) + repo = await create_repo(session=session, project_id=project.id) + backend = await create_backend(session=session, project_id=project.id) + gateway = await create_gateway( + session=session, + project_id=project.id, + backend_id=backend.id, + status=GatewayStatus.RUNNING, + ) + replica = await create_gateway_replica( + session=session, + gateway_id=gateway.id, + backend=backend, + status=GatewayReplicaStatus.RUNNING, + ) + run, _ = await self._create_service_run_and_job( + session, project, repo, user, gateway, run_name="test-service" + ) + _lock_replica(replica) + await session.commit() + + client_mock = _get_client_mock(mock_gateway_connection) + client_mock.get_state_summary.return_value = None + client_mock.list_services.return_value = [] + + await worker.process(_replica_to_pipeline_item(replica)) + + client_mock.list_services.assert_awaited_once() + client_mock.submit_gateway_config.assert_not_called() + assert client_mock.register_service.call_args.kwargs["run_id"] == run.id + async def test_unregisters_dangling_service_and_stale_replica( self, test_db, @@ -1170,23 +1337,26 @@ async def test_unregisters_dangling_service_and_stale_replica( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run1.id.hex, - project_name=project.name, - run_name="live-service", - replicas=[ - ServiceListReplicaItem(id=job1.id.hex), - ServiceListReplicaItem(id=stale_job.id.hex), - ], - ), - ServiceListItem( - id=run2.id.hex, - project_name=project.name, - run_name="dangling-service", - replicas=[], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run1.id.hex, + project_name=project.name, + run_name="live-service", + replicas=[ + ServiceListReplicaItem(id=job1.id.hex), + ServiceListReplicaItem(id=stale_job.id.hex), + ], + ), + ServiceListItem( + id=run2.id.hex, + project_name=project.name, + run_name="dangling-service", + replicas=[], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1306,23 +1476,26 @@ async def test_deletes_registration_models_for_unregistered_service_and_replica( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run1.id.hex, - project_name=project.name, - run_name="live-service", - replicas=[ - ServiceListReplicaItem(id=job1.id.hex), - ServiceListReplicaItem(id=stale_job.id.hex), - ], - ), - ServiceListItem( - id=run2.id.hex, - project_name=project.name, - run_name="dangling-service", - replicas=[], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run1.id.hex, + project_name=project.name, + run_name="live-service", + replicas=[ + ServiceListReplicaItem(id=job1.id.hex), + ServiceListReplicaItem(id=stale_job.id.hex), + ], + ), + ServiceListItem( + id=run2.id.hex, + project_name=project.name, + run_name="dangling-service", + replicas=[], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1426,14 +1599,17 @@ async def test_unregisters_replicas_of_dangling_service_without_extra_gateway_ca await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run.id.hex, - project_name=project.name, - run_name="dangling-service", - replicas=[ServiceListReplicaItem(id=job.id.hex)], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run.id.hex, + project_name=project.name, + run_name="dangling-service", + replicas=[ServiceListReplicaItem(id=job.id.hex)], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1498,14 +1674,17 @@ async def test_no_gateway_calls_when_state_already_in_sync( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run.id.hex, - project_name=project.name, - run_name="synced-service", - replicas=[ServiceListReplicaItem(id=job.id.hex)], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run.id.hex, + project_name=project.name, + run_name="synced-service", + replicas=[ServiceListReplicaItem(id=job.id.hex)], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1570,15 +1749,18 @@ async def test_recovers_legacy_service_id_by_matching_replica( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - # Pre-0.21.0 gateways report services without an id. - ServiceListItem( - id=None, - project_name=project.name, - run_name="legacy-service", - replicas=[ServiceListReplicaItem(id=job.id.hex)], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + # Pre-0.21.0 gateways report services without an id. + ServiceListItem( + id=None, + project_name=project.name, + run_name="legacy-service", + replicas=[ServiceListReplicaItem(id=job.id.hex)], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1620,17 +1802,20 @@ async def test_unregisters_and_reregisters_legacy_service_without_id_and_replica await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - # A legacy entry with no ID and no replicas: there's nothing to match - # it against, so it cannot be told apart from genuine garbage and must - # be unregistered. The real, still-expected run gets registered fresh. - ServiceListItem( - id=None, - project_name=project.name, - run_name="legacy-service", - replicas=[], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + # A legacy entry with no ID and no replicas: there's nothing to match + # it against, so it cannot be told apart from genuine garbage and must + # be unregistered. The real, still-expected run gets registered fresh. + ServiceListItem( + id=None, + project_name=project.name, + run_name="legacy-service", + replicas=[], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1734,14 +1919,17 @@ async def test_does_nothing_when_in_sync_and_registrations_already_exist( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run.id.hex, - project_name=project.name, - run_name="synced-service", - replicas=[ServiceListReplicaItem(id=job.id.hex)], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run.id.hex, + project_name=project.name, + run_name="synced-service", + replicas=[ServiceListReplicaItem(id=job.id.hex)], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1833,14 +2021,17 @@ async def test_reconciles_out_of_sync_registration_models( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run.id.hex, - project_name=project.name, - run_name="drifted-service", - replicas=[ServiceListReplicaItem(id=job.id.hex)], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run.id.hex, + project_name=project.name, + run_name="drifted-service", + replicas=[ServiceListReplicaItem(id=job.id.hex)], + ), + ], + ) await worker.process(_replica_to_pipeline_item(replica)) @@ -1930,7 +2121,7 @@ async def test_propagates_registration_errors_and_increments_register_attempt( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) async def register_service_side_effect(**kwargs): if kwargs["run_name"] == "service-fails": @@ -2045,7 +2236,7 @@ async def test_does_not_emit_duplicate_registration_error_event_for_unchanged_er ) client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) client_mock.register_replica.side_effect = GatewayError("boom replica") # First tick: the replica registration fails, recording the error and @@ -2155,23 +2346,26 @@ async def test_propagates_unregistration_errors_and_increments_unregister_attemp await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run.id.hex, - project_name=project.name, - run_name="live-service", - replicas=[ - ServiceListReplicaItem(id=job.id.hex), - ServiceListReplicaItem(id=stale_job.id.hex), - ], - ), - ServiceListItem( - id=dangling_run.id.hex, - project_name=project.name, - run_name="dangling-service", - replicas=[], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run.id.hex, + project_name=project.name, + run_name="live-service", + replicas=[ + ServiceListReplicaItem(id=job.id.hex), + ServiceListReplicaItem(id=stale_job.id.hex), + ], + ), + ServiceListItem( + id=dangling_run.id.hex, + project_name=project.name, + run_name="dangling-service", + replicas=[], + ), + ], + ) client_mock.unregister_service.side_effect = make_error("boom service") client_mock.unregister_replica.side_effect = make_error("boom replica") @@ -2248,17 +2442,20 @@ async def test_does_not_emit_duplicate_unregistration_error_event_for_unchanged_ await session.commit() client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [ - ServiceListItem( - id=run.id.hex, - project_name=project.name, - run_name="live-service", - replicas=[ - ServiceListReplicaItem(id=job.id.hex), - ServiceListReplicaItem(id=stale_job.id.hex), - ], - ), - ] + client_mock.get_state_summary.return_value = _get_state_summary( + replica, + [ + ServiceListItem( + id=run.id.hex, + project_name=project.name, + run_name="live-service", + replicas=[ + ServiceListReplicaItem(id=job.id.hex), + ServiceListReplicaItem(id=stale_job.id.hex), + ], + ), + ], + ) client_mock.unregister_replica.side_effect = GatewayError("boom replica") # First tick: unregistering the stale replica fails, recording the error @@ -2386,7 +2583,7 @@ async def test_registers_imports_of_exported_models_that_services_serve( exported_models=["exported-model", "not-served-model"], ) client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) client_mock.list_imports.return_value = [] await worker.process(_replica_to_pipeline_item(replica)) @@ -2425,7 +2622,7 @@ async def test_unregisters_import_when_export_importer_project_model_or_run_chan exported_models=["test-model"], ) client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) client_mock.list_imports.return_value = [ ImportListItem( importer_project="importer", @@ -2486,7 +2683,7 @@ async def test_registers_import_from_older_export_and_moves_it_once_export_is_de await session.commit() newer_export_id, older_export_id = newer_export.id, older_export.id client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) client_mock.list_imports.return_value = [] await worker.process(_replica_to_pipeline_item(replica)) @@ -2554,7 +2751,7 @@ async def test_unregisters_imports_on_gateway_with_project_name_in_domain( exported_models=["test-model"], ) client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) # Registered while the gateway had a fixed domain. client_mock.list_imports.return_value = [ ImportListItem( @@ -2596,7 +2793,7 @@ async def test_syncs_services_but_not_imports_if_gateway_has_no_import_routes( exported_models=["test-model"], ) client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) request = Request("GET", "http://gateway/api/registry/imports/list") client_mock.list_imports.side_effect = HTTPStatusError( "Not Found", request=request, response=Response(404, request=request) @@ -2637,7 +2834,7 @@ async def test_does_not_sync_imports_if_exports_are_disabled( exported_models=["test-model"], ) client_mock = _get_client_mock(mock_gateway_connection) - client_mock.list_services.return_value = [] + client_mock.get_state_summary.return_value = _get_state_summary(replica, []) await worker.process(_replica_to_pipeline_item(replica)) @@ -2959,7 +3156,7 @@ async def test_provisioning_to_terminating_if_connect_fails( assert replica.status_message == "Failed to connect to gateway replica" @pytest.mark.parametrize("legacy_replica", [False, True]) - async def test_provisioning_to_terminating_if_configure_fails( + async def test_provisioning_to_terminating_if_app_not_available( self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, legacy_replica: bool ): project = await create_project(session=session) @@ -2992,19 +3189,19 @@ async def test_provisioning_to_terminating_if_configure_fails( "dstack._internal.server.services.gateways.connect_to_gateway_replica_with_retry" ) as connect_mock, patch( - "dstack._internal.server.services.gateways.configure_gateway_replica" - ) as configure_mock, + "dstack._internal.server.services.gateways.wait_for_gateway_replica_app" + ) as wait_mock, ): connect_mock.return_value = MagicMock() - configure_mock.side_effect = Exception("Configure failed") + wait_mock.side_effect = Exception("App not available") await worker.process(_replica_to_pipeline_item(replica)) connect_mock.assert_called_once() - configure_mock.assert_called_once() + wait_mock.assert_called_once() await session.refresh(replica) assert replica.status == GatewayReplicaStatus.TERMINATING assert replica.active is False - assert replica.status_message == "Failed to configure gateway replica" + assert replica.status_message == "Gateway replica app is not available" @pytest.mark.parametrize( "gateway_status,to_be_deleted", @@ -3050,7 +3247,7 @@ async def test_provisioning_to_terminating_if_gateway_needs_cleanup( await session.commit() with patch( - "dstack._internal.server.background.pipeline_tasks.gateway_replicas._connect_and_configure_gateway_replica" + "dstack._internal.server.background.pipeline_tasks.gateway_replicas._connect_to_gateway_replica" ) as connect_mock: await worker.process(_replica_to_pipeline_item(replica)) connect_mock.assert_not_called() diff --git a/src/tests/_internal/server/routers/test_gateways.py b/src/tests/_internal/server/routers/test_gateways.py index 9966c47764..2af2b335f6 100644 --- a/src/tests/_internal/server/routers/test_gateways.py +++ b/src/tests/_internal/server/routers/test_gateways.py @@ -3215,52 +3215,6 @@ async def test_creates_gateway_with_secret_references( events = await list_events(session) assert all("s3cret" not in e.message for e in events) - async def test_cannot_update_otel_in_place( - self, test_db, session: AsyncSession, client: AsyncClient - ): - user = await create_user(session, global_role=GlobalRole.USER) - project = await create_project(session) - await add_project_member( - session=session, project=project, user=user, project_role=ProjectRole.ADMIN - ) - backend = await create_backend(session, project.id, backend_type=BackendType.AWS) - gateway = await create_gateway( - session=session, - project_id=project.id, - backend_id=backend.id, - name="my-gateway", - region="us-east-1", - ) - await create_gateway_replica(session=session, backend=backend, gateway_id=gateway.id) - get_response = await client.post( - f"/api/project/{project.name}/gateways/get", - json={"name": "my-gateway"}, - headers=get_auth_headers(user.token), - ) - - response = await client.post( - f"/api/project/{project.name}/gateways/apply", - json={ - "plan": { - "spec": { - "configuration": { - "type": "gateway", - "name": "my-gateway", - "backend": "aws", - "region": "us-east-1", - "otel": {"endpoint": "https://otlp.example.com", "traces": True}, - } - }, - "current_resource": get_response.json(), - }, - "force": False, - }, - headers=get_auth_headers(user.token), - ) - - assert response.status_code == 400 - assert "cannot be updated in-place" in response.json()["detail"][0]["msg"] - async def test_rejects_missing_secret( self, test_db, session: AsyncSession, client: AsyncClient ): diff --git a/src/tests/_internal/server/services/gateways/test_gateways.py b/src/tests/_internal/server/services/gateways/test_gateways.py index 6284d69bff..f30dd4dbe9 100644 --- a/src/tests/_internal/server/services/gateways/test_gateways.py +++ b/src/tests/_internal/server/services/gateways/test_gateways.py @@ -11,10 +11,12 @@ from dstack._internal.core.models.gateways import GatewayConfiguration, GatewayOTelConfig from dstack._internal.proxy.gateway.const import SERVICE_SCALING_WINDOWS from dstack._internal.proxy.gateway.schemas.stats import Stat +from dstack._internal.proxy.gateway.testing.common import make_otel_settings from dstack._internal.server.services import gateways from dstack._internal.server.services.gateways import ( _merge_per_window_stats, _validate_gateway_configuration, + build_gateway_config, get_gateway_replica_models, ) from dstack._internal.server.testing.common import ( @@ -133,13 +135,6 @@ async def test_runs_install_command_on_existing_gateway_replicas( "get_or_add", AsyncMock(return_value=connection), ) - monkeypatch.setattr( - gateways.gateway_connections_pool, - "all", - AsyncMock(return_value=[connection]), - ) - configure = AsyncMock() - monkeypatch.setattr(gateways, "configure_gateway_replica", configure) project = await create_project(session=session) backend = await create_backend(session=session, project_id=project.id) replica = await create_gateway_replica(session=session, backend=backend) @@ -151,56 +146,8 @@ async def test_runs_install_command_on_existing_gateway_replicas( connection.tunnel.aexec.assert_awaited_once_with( get_dstack_gateway_install_command(), timeout=ANY ) - configure.assert_awaited_once() assert replica.app_updated_at == (now if updated else previously_updated_at) - async def test_configures_replicas_with_otel_settings( - self, session: AsyncSession, monkeypatch: pytest.MonkeyPatch - ): - connection = Mock(ip_address="1.1.1.1") - monkeypatch.setattr(gateways.settings, "SKIP_GATEWAY_UPDATE", True) - monkeypatch.setattr( - gateways.gateway_connections_pool, "get_or_add", AsyncMock(return_value=connection) - ) - monkeypatch.setattr( - gateways.gateway_connections_pool, "all", AsyncMock(return_value=[connection]) - ) - configure = AsyncMock() - monkeypatch.setattr(gateways, "configure_gateway_replica", configure) - project = await create_project(session=session, name="main") - backend = await create_backend(session=session, project_id=project.id) - gateway = await create_gateway( - session=session, project_id=project.id, backend_id=backend.id, name="my-gateway" - ) - configuration = gateways.get_gateway_configuration(gateway) - configuration.otel = GatewayOTelConfig( - endpoint="https://otlp", - headers={"Authorization": "Bearer ${{ secrets.token }}"}, - traces=True, - ) - gateway.configuration = configuration.model_dump_json() - await create_secret(session=session, project=project, name="token", value="s3cret") - replica = await create_gateway_replica( - session=session, backend=backend, gateway_id=gateway.id, replica_num=1 - ) - await session.commit() - # Relationships must be loaded by init_gateways, not come from the identity map - session.expunge_all() - - await gateways.init_gateways(session) - - configure.assert_awaited_once() - assert configure.await_args is not None - assert configure.await_args.args[0] is connection - otel_settings = configure.await_args.args[1] - assert otel_settings.traces_enabled - assert otel_settings.headers == {"Authorization": "Bearer s3cret"} - attributes = otel_settings.resource_attributes - assert attributes["service.instance.id"] == str(replica.id) - assert attributes["dstack.project.name"] == "main" - assert attributes["dstack.gateway.name"] == "my-gateway" - assert attributes["dstack.backend"] == backend.type.value - @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) @@ -241,3 +188,17 @@ async def test_does_not_use_other_projects_secrets(self, test_db, session: Async def _make_otel_configuration(otel: GatewayOTelConfig) -> GatewayConfiguration: return GatewayConfiguration(backend=BackendType.AWS, region="us-east-1", otel=otel) + + +class TestBuildGatewayConfig: + def test_hash_depends_on_config_and_key(self): + otel_settings = make_otel_settings(headers={"Authorization": "Bearer s3cret"}) + + config = build_gateway_config(otel_settings, hash_key="key") + + assert config.otel_settings == otel_settings + assert config.config_hash == build_gateway_config(otel_settings, "key").config_hash + assert config.config_hash != build_gateway_config(None, "key").config_hash + assert config.config_hash != build_gateway_config(otel_settings, "other").config_hash + other_otel_settings = make_otel_settings(headers={"Authorization": "Bearer other"}) + assert config.config_hash != build_gateway_config(other_otel_settings, "key").config_hash