Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
ReplicaProxyJumpKeyUpdate,
)
from dstack._internal.proxy.gateway.schemas.services import ServiceListItem
from dstack._internal.proxy.gateway.schemas.state import StateSummaryResponse
from dstack._internal.server import settings
from dstack._internal.server.background.pipeline_tasks.base import (
Fetcher,
Expand Down Expand Up @@ -539,6 +540,7 @@ async def _process_provisioning_item(item: GatewayReplicaPipelineItem):
GatewayReplicaModel.instance_id,
GatewayReplicaModel.backend_id,
GatewayReplicaModel.configuration,
GatewayReplicaModel.region,
],
gateway_fields=_GATEWAY_FIELDS_MIN
+ [
Expand All @@ -563,8 +565,8 @@ 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_to_gateway_replica(replica_model)
if error is not None:
connection, error = await _connect_to_gateway_replica(replica_model)
if connection is None:
await _commit_update(
item,
replica_model,
Expand All @@ -574,6 +576,26 @@ async def _process_provisioning_item(item: GatewayReplicaPipelineItem):
)
return

# Sync before the replica gets traffic from the load balancer, so that it serves
# all services from the start. Fatal, like the other provisioning steps.
replica_state = await _get_gateway_replica_state(connection, replica_model)
state_sync = None
if replica_state is not None:
state_sync = await _sync_gateway_replica_state(
connection, gateway_model, replica_model, replica_state
)
if state_sync is None:
await _commit_update(
item,
replica_model,
_GatewayReplicaUpdateMap(
status=GatewayReplicaStatus.TERMINATING,
status_message="Failed to sync gateway replica state",
active=False,
),
)
return

if gateway_model.hostname is not None:
reg_error = await _register_replica_with_load_balancer(gateway_model, replica_model)
if reg_error is not None:
Expand All @@ -588,11 +610,15 @@ async def _process_provisioning_item(item: GatewayReplicaPipelineItem):
)
return

await _commit_update(
item,
replica_model,
_GatewayReplicaUpdateMap(status=GatewayReplicaStatus.RUNNING, active=True),
)
async with get_session_ctx() as session:
if not await _apply_update(
session,
item,
replica_model,
_GatewayReplicaUpdateMap(status=GatewayReplicaStatus.RUNNING, active=True),
):
return
await _save_state_sync(session, replica_model, state_sync)


async def _register_replica_with_load_balancer(
Expand Down Expand Up @@ -627,8 +653,10 @@ async def _register_replica_with_load_balancer(
return None


async def _connect_to_gateway_replica(gateway_replica: GatewayReplicaModel) -> Optional[str]:
"""Returns an error message on failure, None on success."""
async def _connect_to_gateway_replica(
gateway_replica: GatewayReplicaModel,
) -> tuple[Optional[GatewayConnection], Optional[str]]:
"""Returns the connection on success, or `None` and an error message on failure."""
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 wait_for_gateway_replica_app now has
Expand All @@ -638,14 +666,14 @@ async def _connect_to_gateway_replica(gateway_replica: GatewayReplicaModel) -> O
# - only one server replica is processing the gateway replica
connection = await gateways_services.connect_to_gateway_replica_with_retry(gateway_replica)
if connection is None:
return "Failed to connect to gateway replica"
return None, "Failed to connect to gateway replica"
try:
await gateways_services.wait_for_gateway_replica_app(connection)
except Exception:
logger.exception("%s: gateway replica app is not available", fmt(gateway_replica))
return "Gateway replica app is not available"
return None, "Gateway replica app is not available"
logger.info("%s: gateway replica connected", fmt(gateway_replica))
return None
return connection, None


async def _process_running_item(item: GatewayReplicaPipelineItem):
Expand Down Expand Up @@ -685,13 +713,73 @@ async def _process_running_item(item: GatewayReplicaPipelineItem):
logger.warning("%s: failed to connect to gateway: %s", fmt(replica_model), e)
await _commit_update(item, replica_model, update_map={})
return
replica_state = await _get_gateway_replica_state(connection, replica_model)
if replica_state is None:
await _commit_update(item, replica_model, update_map={})
return
await _run_process_running_gateway_replica_hooks(replica_model, connection)
state_sync = await _sync_gateway_replica_state(
connection, gateway_model, replica_model, replica_state
)
if state_sync is None:
await _commit_update(item, replica_model, update_map={})
return
async with get_session_ctx() as session:
if not await _apply_update(session, item, replica_model, update_map={}):
return
await _save_state_sync(session, replica_model, state_sync)


_PROCESS_RUNNING_GATEWAY_REPLICA_HOOKS: list[
Callable[[uuid.UUID, GatewayConnection], Awaitable[None]]
] = []


def register_process_running_gateway_replica_hook(
func: Callable[[uuid.UUID, GatewayConnection], Awaitable[None]],
):
"""
Registers `func` to be called with the ID of a running gateway replica and the connection
to it each time `GatewayReplicaPipeline` processes the replica and the replica responds.

The pipeline keeps the replica locked during the call, so server replicas do not call `func`
for the same gateway replica at once, unless the lock expires. `func` should not take long,
since the replica's services are synced only after it returns. If `func` raises,
the error is logged, and the replica is processed further.
"""
_PROCESS_RUNNING_GATEWAY_REPLICA_HOOKS.append(func)


async def _run_process_running_gateway_replica_hooks(
replica_model: GatewayReplicaModel, connection: GatewayConnection
) -> None:
for hook in _PROCESS_RUNNING_GATEWAY_REPLICA_HOOKS:
try:
await hook(replica_model.id, connection)
except Exception:
logger.exception("%s: process running gateway replica hook failed", fmt(replica_model))


@dataclass
class _GatewayReplicaState:
state_summary: Optional[StateSummaryResponse]
"""`None` for gateways that cannot report it. The config is not synced then."""
services: list[ServiceListItem]
imports: Optional[list[ImportListItem]]
"""`None` if the imports are not synced."""


async def _get_gateway_replica_state(
connection: GatewayConnection, replica_model: GatewayReplicaModel
) -> Optional[_GatewayReplicaState]:
"""Returns `None` if the state cannot be fetched."""
async with connection.client() as client:
try:
state_summary = await client.get_state_summary()
if state_summary is not None:
currently_registered_services = state_summary.services
services = state_summary.services
else:
currently_registered_services = await client.list_services()
services = await client.list_services()
except Exception as e:
if isinstance(e, HTTPStatusError) and e.response.status_code == 404:
logger.warning(
Expand All @@ -703,33 +791,74 @@ async def _process_running_item(item: GatewayReplicaPipelineItem):
)
else:
logger.warning("%s: failed to get gateway state: %r", fmt(replica_model), e)
await _commit_update(item, replica_model, update_map={})
return
return None
# Imports are synced only where exports are enabled.
currently_registered_imports = None
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)
imports = await _list_imports(client, replica_model)
return _GatewayReplicaState(state_summary=state_summary, services=services, imports=imports)


async def _list_imports(
client: GatewayClient, replica_model: GatewayReplicaModel
) -> Optional[list[ImportListItem]]:
"""Returns `None` if the imports cannot be listed. They are not synced then."""
try:
return await client.list_imports()
except Exception as e:
if isinstance(e, HTTPStatusError) and e.response.status_code == 404:
logger.debug(
(
"%s: got error 404 when listing imports, which indicates a gateway"
" that is not updated yet. Skipping imports sync until the gateway is updated"
),
fmt(replica_model),
)
else:
logger.warning("%s: failed to list imports: %r", fmt(replica_model), e)
return None


@dataclass
class _PerformedStateSync:
"""A state sync performed on the gateway replica, to be saved to the DB."""

initially_registered_services: list[ServiceListItem]
run_models_by_id: dict[uuid.UUID, RunModel]
job_models_by_id: dict[uuid.UUID, JobModel]
result: "_StateSyncResult"


async def _sync_gateway_replica_state(
connection: GatewayConnection,
gateway_model: GatewayModel,
replica_model: GatewayReplicaModel,
replica_state: _GatewayReplicaState,
) -> Optional[_PerformedStateSync]:
"""
Syncs the gateway config, then the services, replicas, and imports.
Returns `None` if the services were not synced. Failed registrations of individual services
or replicas do not prevent the sync, they are recorded in the result.
"""
state_summary = replica_state.state_summary
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
# Do not attempt service registration - we failed to submit the config,
# so the gateway may attempt to request certificates from the wrong ACME server
return None
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
return None
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]
if currently_registered_imports is not None:
if replica_state.imports is not None:
# The imports that the replica should have follow from the models of its services.
run_fields += [RunModel.project_id, RunModel.service_spec]
stmt = (
Expand Down Expand Up @@ -758,7 +887,7 @@ async def _process_running_item(item: GatewayReplicaPipelineItem):
)
instance_connection_info = res.all()
expected_imports: set[_ImportRef] = set()
if currently_registered_imports is not None:
if replica_state.imports is not None:
expected_imports = await _get_expected_imports(session, gateway_model, expected_runs)

# Parse keys and compare gateway state without holding a DB connection.
Expand All @@ -775,10 +904,10 @@ async def _process_running_item(item: GatewayReplicaPipelineItem):
)
instance_proxy_jump_public_keys[instance_id] = public_key
plan = _plan_state_sync(
currently_registered=currently_registered_services,
currently_registered=replica_state.services,
expected=expected_runs,
instance_proxy_jump_public_keys=instance_proxy_jump_public_keys,
currently_registered_imports=currently_registered_imports,
currently_registered_imports=replica_state.imports,
expected_imports=expected_imports,
)
async with get_session_ctx() as session:
Expand All @@ -790,70 +919,28 @@ async def _process_running_item(item: GatewayReplicaPipelineItem):
connection, gateway_model, replica_model, run_models_by_id, job_models_by_id, plan
)

async with get_session_ctx() as session:
if not await _apply_update(session, item, replica_model, update_map={}):
return
reconcile_records_result = await _reconcile_registration_records(
session, replica_model, currently_registered_services, sync_result
)
await _emit_state_sync_events(
session,
replica_model,
run_models_by_id,
job_models_by_id,
sync_result,
reconcile_records_result,
)


_PROCESS_RUNNING_GATEWAY_REPLICA_HOOKS: list[
Callable[[uuid.UUID, GatewayConnection], Awaitable[None]]
] = []


def register_process_running_gateway_replica_hook(
func: Callable[[uuid.UUID, GatewayConnection], Awaitable[None]],
):
"""
Registers `func` to be called with the ID of a running gateway replica and the connection
to it each time `GatewayReplicaPipeline` processes the replica and the replica responds.

The pipeline keeps the replica locked during the call, so server replicas do not call `func`
for the same gateway replica at once, unless the lock expires. `func` should not take long,
since the replica's services are synced only after it returns. If `func` raises,
the error is logged, and the replica is processed further.
"""
_PROCESS_RUNNING_GATEWAY_REPLICA_HOOKS.append(func)
return _PerformedStateSync(
initially_registered_services=replica_state.services,
run_models_by_id=run_models_by_id,
job_models_by_id=job_models_by_id,
result=sync_result,
)


async def _run_process_running_gateway_replica_hooks(
replica_model: GatewayReplicaModel, connection: GatewayConnection
async def _save_state_sync(
session: AsyncSession, replica_model: GatewayReplicaModel, state_sync: _PerformedStateSync
) -> None:
for hook in _PROCESS_RUNNING_GATEWAY_REPLICA_HOOKS:
try:
await hook(replica_model.id, connection)
except Exception:
logger.exception("%s: process running gateway replica hook failed", fmt(replica_model))


async def _list_imports(
client: GatewayClient, replica_model: GatewayReplicaModel
) -> Optional[list[ImportListItem]]:
"""Returns `None` if the imports cannot be listed. They are not synced then."""
try:
return await client.list_imports()
except Exception as e:
if isinstance(e, HTTPStatusError) and e.response.status_code == 404:
logger.debug(
(
"%s: got error 404 when listing imports, which indicates a gateway"
" that is not updated yet. Skipping imports sync until the gateway is updated"
),
fmt(replica_model),
)
else:
logger.warning("%s: failed to list imports: %r", fmt(replica_model), e)
return None
reconcile_records_result = await _reconcile_registration_records(
session, replica_model, state_sync.initially_registered_services, state_sync.result
)
await _emit_state_sync_events(
session,
replica_model,
state_sync.run_models_by_id,
state_sync.job_models_by_id,
state_sync.result,
reconcile_records_result,
)


async def _get_expected_imports(
Expand Down
Loading
Loading