From c5c4685367b8c174732882626f76436fe1f91fc1 Mon Sep 17 00:00:00 2001 From: Dmitry Meyer Date: Tue, 1 Dec 2026 15:42:14 +0000 Subject: [PATCH] Register gateway replicas with load balancer after first sync A new gateway replica was registered with the load balancer and marked running as soon as its gateway app came up. Services were registered on it only by the first sync of the running replica, at least 15 seconds later. In the meantime, the load balancer already sent requests to the replica, which answered them with the nginx default site or 404s, and then with 503s until the service replicas were registered. Run the first sync while provisioning, before registering the replica with the load balancer. If the sync fails, the replica is terminated, like when other provisioning steps fail. Failed registrations of individual services or service replicas do not block the replica, and later syncs retry them, as on any running replica. Part-of: https://github.com/dstackai/dstack/issues/4566 Assisted-by: Claude Opus 5.5 --- .../pipeline_tasks/gateway_replicas.py | 267 ++++++++++++------ .../pipeline_tasks/test_gateway_replicas.py | 256 +++++++++++++---- 2 files changed, 380 insertions(+), 143 deletions(-) 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 7ea770cc2..c63e33f1a 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py @@ -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, @@ -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 + [ @@ -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, @@ -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: @@ -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( @@ -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 @@ -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): @@ -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( @@ -703,13 +791,56 @@ 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( @@ -717,19 +848,17 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): ) 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 = ( @@ -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. @@ -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: @@ -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( 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 dd0a8c62d..d4f59b1b4 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 @@ -44,6 +44,7 @@ GatewayModel, GatewayReplicaModel, ImportModel, + JobModel, ProjectModel, RunModel, ServiceRegistrationModel, @@ -56,7 +57,6 @@ get_gateway_configuration, ) from dstack._internal.server.testing.common import ( - AsyncContextManager, ComputeMockSpec, create_backend, create_export, @@ -2847,6 +2847,39 @@ async def test_does_not_sync_imports_if_exports_are_disabled( @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestGatewayReplicaWorkerProvisioning: + @pytest.fixture + def client_mock(self, mock_gateway_connection: AsyncMock) -> AsyncMock: + """The client of a freshly installed gateway app, with no services and no config.""" + client_mock = _get_client_mock(mock_gateway_connection) + client_mock.get_state_summary.return_value = StateSummaryResponse( + services=[], config_hash=None + ) + return client_mock + + async def _create_service_run_and_job( + self, session: AsyncSession, project: ProjectModel, gateway: GatewayModel + ) -> tuple[RunModel, JobModel]: + user = await create_user(session=session) + repo = await create_repo(session=session, project_id=project.id) + run = await create_service_run( + session=session, project=project, repo=repo, user=user, gateway=gateway + ) + fleet = await create_fleet(session=session, project=project) + instance = await create_instance( + session=session, project=project, status=InstanceStatus.BUSY, fleet=fleet + ) + job = await create_job( + session=session, + run=run, + status=JobStatus.RUNNING, + job_provisioning_data=get_job_provisioning_data(dockerized=True), + instance=instance, + instance_assigned=True, + registered=True, + ready=True, + ) + return run, job + @pytest.mark.parametrize("legacy_replica", [False, True]) @pytest.mark.parametrize("populate_configuration", [True, False]) async def test_provisioning_to_running( @@ -2854,6 +2887,8 @@ async def test_provisioning_to_running( test_db, session: AsyncSession, worker: GatewayReplicaWorker, + mock_gateway_connection: AsyncMock, + client_mock: AsyncMock, legacy_replica: bool, populate_configuration: bool, ): @@ -2885,20 +2920,16 @@ async def test_provisioning_to_running( _lock_replica(replica) await session.commit() - with patch( - "dstack._internal.server.services.gateways.gateway_connections_pool.get_or_add" - ) as pool_add: - pool_add.return_value = MagicMock() - pool_add.return_value.client.return_value = MagicMock(AsyncContextManager()) - await worker.process(_replica_to_pipeline_item(replica)) - pool_add.assert_called_once() + await worker.process(_replica_to_pipeline_item(replica)) + mock_gateway_connection.assert_called_once() + client_mock.submit_gateway_config.assert_awaited_once() await session.refresh(replica) assert replica.status == GatewayReplicaStatus.RUNNING assert replica.active is True async def test_provisioning_to_running_registers_with_load_balancer( - self, test_db, session: AsyncSession, worker: GatewayReplicaWorker + self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, client_mock: AsyncMock ): project = await create_project(session=session) backend = await create_backend(session=session, project_id=project.id) @@ -2921,17 +2952,10 @@ async def test_provisioning_to_running_registers_with_load_balancer( await session.commit() backend_mock = Mock() - with ( - patch( - "dstack._internal.server.services.gateways.gateway_connections_pool.get_or_add" - ) as pool_add, - patch( - "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", - mock_lease(backend_mock), - ), + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", + mock_lease(backend_mock), ): - pool_add.return_value = MagicMock() - pool_add.return_value.client.return_value = MagicMock(AsyncContextManager()) backend_mock.compute.return_value = Mock(spec=ComputeMockSpec) await worker.process(_replica_to_pipeline_item(replica)) @@ -2950,7 +2974,7 @@ async def test_provisioning_to_running_registers_with_load_balancer( assert replica.active is True async def test_provisioning_skips_load_balancer_registration_without_hostname( - self, test_db, session: AsyncSession, worker: GatewayReplicaWorker + self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, client_mock: AsyncMock ): project = await create_project(session=session) backend = await create_backend(session=session, project_id=project.id) @@ -2969,17 +2993,9 @@ async def test_provisioning_skips_load_balancer_registration_without_hostname( _lock_replica(replica) await session.commit() - with ( - patch( - "dstack._internal.server.services.gateways.gateway_connections_pool.get_or_add" - ) as pool_add, - patch( - "dstack._internal.server.services.backends.cache.lease_project_backend_by_id" - ) as get_backends_mock, - ): - pool_add.return_value = MagicMock() - pool_add.return_value.client.return_value = MagicMock(AsyncContextManager()) - + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_id" + ) as get_backends_mock: await worker.process(_replica_to_pipeline_item(replica)) get_backends_mock.assert_not_called() @@ -2989,7 +3005,7 @@ async def test_provisioning_skips_load_balancer_registration_without_hostname( assert replica.active is True async def test_provisioning_to_terminating_when_load_balancer_registration_fails( - self, test_db, session: AsyncSession, worker: GatewayReplicaWorker + self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, client_mock: AsyncMock ): project = await create_project(session=session) backend = await create_backend(session=session, project_id=project.id) @@ -3012,17 +3028,10 @@ async def test_provisioning_to_terminating_when_load_balancer_registration_fails await session.commit() backend_mock = Mock() - with ( - patch( - "dstack._internal.server.services.gateways.gateway_connections_pool.get_or_add" - ) as pool_add, - patch( - "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", - mock_lease(backend_mock), - ), + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", + mock_lease(backend_mock), ): - pool_add.return_value = MagicMock() - pool_add.return_value.client.return_value = MagicMock(AsyncContextManager()) backend_mock.compute.return_value = Mock(spec=ComputeMockSpec) backend_mock.compute.return_value.register_gateway_replica_with_load_balancer.side_effect = Exception( "boom" @@ -3036,7 +3045,7 @@ async def test_provisioning_to_terminating_when_load_balancer_registration_fails assert replica.status_message == "Error registering with load balancer" async def test_provisioning_to_terminating_when_backend_does_not_support_load_balancer( - self, test_db, session: AsyncSession, worker: GatewayReplicaWorker + self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, client_mock: AsyncMock ): project = await create_project(session=session) backend = await create_backend(session=session, project_id=project.id) @@ -3059,17 +3068,10 @@ async def test_provisioning_to_terminating_when_backend_does_not_support_load_ba await session.commit() backend_mock = Mock() - with ( - patch( - "dstack._internal.server.services.gateways.gateway_connections_pool.get_or_add" - ) as pool_add, - patch( - "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", - mock_lease(backend_mock), - ), + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", + mock_lease(backend_mock), ): - pool_add.return_value = MagicMock() - pool_add.return_value.client.return_value = MagicMock(AsyncContextManager()) backend_mock.compute.return_value = Mock(spec=ComputeWithGatewaySupport) await worker.process(_replica_to_pipeline_item(replica)) @@ -3079,6 +3081,154 @@ async def test_provisioning_to_terminating_when_backend_does_not_support_load_ba assert replica.active is False assert replica.status_message == "Backend does not support load balancer operations" + @pytest.mark.usefixtures("image_config_mock") + async def test_provisioning_registers_services_before_registering_with_load_balancer( + self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, client_mock: AsyncMock + ): + project = await create_project(session=session) + 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, + wildcard_domain="example.com", + certificate=ACMGatewayCertificate(arn="arn:aws:acm:us:1:certificate/x"), + hostname="gateway-lb.example.com", + backend_data="lb-backend-data", + ) + replica = await create_gateway_replica( + session=session, + gateway_id=gateway.id, + backend=backend, + status=GatewayReplicaStatus.PROVISIONING, + ) + run, job = await self._create_service_run_and_job(session, project, gateway) + _lock_replica(replica) + await session.commit() + + calls = [] + client_mock.register_service.side_effect = lambda **_: calls.append("register_service") + client_mock.register_replica.side_effect = lambda **_: calls.append("register_replica") + backend_mock = Mock() + backend_mock.compute.return_value = Mock(spec=ComputeMockSpec) + backend_mock.compute.return_value.register_gateway_replica_with_load_balancer.side_effect = ( + lambda *_: calls.append("register_with_load_balancer") + ) + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_id", + mock_lease(backend_mock), + ): + await worker.process(_replica_to_pipeline_item(replica)) + + # The load balancer sends traffic only to a replica that serves the services + assert calls == ["register_service", "register_replica", "register_with_load_balancer"] + await session.refresh(replica) + assert replica.status == GatewayReplicaStatus.RUNNING + assert replica.active is True + service_registration = ( + await session.execute( + select(ServiceRegistrationModel).where( + ServiceRegistrationModel.run_id == run.id, + ServiceRegistrationModel.gateway_replica_id == replica.id, + ) + ) + ).scalar_one() + assert service_registration.is_registered is True + replica_registration = ( + await session.execute( + select(ServiceReplicaRegistrationModel).where( + ServiceReplicaRegistrationModel.job_id == job.id, + ServiceReplicaRegistrationModel.gateway_replica_id == replica.id, + ) + ) + ).scalar_one() + assert replica_registration.is_registered is True + events = await list_events(session) + assert {"Service registered", "Service replica registered"} <= {e.message for e in events} + + @pytest.mark.parametrize("failing_method", ["get_state_summary", "submit_gateway_config"]) + async def test_provisioning_to_terminating_if_state_sync_fails( + self, + test_db, + session: AsyncSession, + worker: GatewayReplicaWorker, + client_mock: AsyncMock, + failing_method: str, + ): + project = await create_project(session=session) + 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, + certificate=ACMGatewayCertificate(arn="arn:aws:acm:us:1:certificate/x"), + hostname="gateway-lb.example.com", + backend_data="lb-backend-data", + ) + replica = await create_gateway_replica( + session=session, + gateway_id=gateway.id, + backend=backend, + status=GatewayReplicaStatus.PROVISIONING, + ) + _lock_replica(replica) + await session.commit() + getattr(client_mock, failing_method).side_effect = RuntimeError("gateway unavailable") + + with patch( + "dstack._internal.server.services.backends.cache.lease_project_backend_by_id" + ) as get_backends_mock: + await worker.process(_replica_to_pipeline_item(replica)) + + get_backends_mock.assert_not_called() + + await session.refresh(replica) + assert replica.status == GatewayReplicaStatus.TERMINATING + assert replica.active is False + assert replica.status_message == "Failed to sync gateway replica state" + + @pytest.mark.usefixtures("image_config_mock") + async def test_provisioning_to_running_if_service_registration_fails( + self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, client_mock: AsyncMock + ): + project = await create_project(session=session) + 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, + wildcard_domain="example.com", + ) + replica = await create_gateway_replica( + session=session, + gateway_id=gateway.id, + backend=backend, + status=GatewayReplicaStatus.PROVISIONING, + ) + run, _ = await self._create_service_run_and_job(session, project, gateway) + _lock_replica(replica) + await session.commit() + client_mock.register_service.side_effect = GatewayError("registration failed") + + await worker.process(_replica_to_pipeline_item(replica)) + + # Failed registrations are retried by later syncs, as on any running replica + await session.refresh(replica) + assert replica.status == GatewayReplicaStatus.RUNNING + service_registration = ( + await session.execute( + select(ServiceRegistrationModel).where( + ServiceRegistrationModel.run_id == run.id, + ServiceRegistrationModel.gateway_replica_id == replica.id, + ) + ) + ).scalar_one() + assert service_registration.is_registered is False + assert service_registration.register_status_message == "registration failed" + async def test_provisioning_waits_for_pending_acm_gateway_migration( self, test_db, session: AsyncSession, worker: GatewayReplicaWorker ):