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
7 changes: 6 additions & 1 deletion src/dstack/_internal/core/models/gateways.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions src/dstack/_internal/proxy/gateway/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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("/")
Expand Down
2 changes: 2 additions & 0 deletions src/dstack/_internal/proxy/gateway/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
1 change: 1 addition & 0 deletions src/dstack/_internal/proxy/gateway/routers/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 3 additions & 1 deletion src/dstack/_internal/proxy/gateway/routers/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
19 changes: 19 additions & 0 deletions src/dstack/_internal/proxy/gateway/routers/state.py
Original file line number Diff line number Diff line change
@@ -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)
1 change: 1 addition & 0 deletions src/dstack/_internal/proxy/gateway/schemas/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 12 additions & 0 deletions src/dstack/_internal/proxy/gateway/schemas/state.py
Original file line number Diff line number Diff line change
@@ -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"""
Original file line number Diff line number Diff line change
Expand Up @@ -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
+ [
Expand All @@ -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:
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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


Expand Down Expand Up @@ -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(
Expand All @@ -707,14 +702,30 @@ 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.
currently_registered_imports = None
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]
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading