Skip to content
Closed
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
54 changes: 54 additions & 0 deletions contributing/PROXY.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,57 @@ sqlite3 ~/.dstack/server/data/sqlite.db "SELECT ssh_private_key FROM gateway_com
chmod 600 /tmp/gateway.key
ssh -i /tmp/gateway.key ubuntu@$GATEWAY_IP_ADDR sudo journalctl -u dstack.gateway.service
```

## Gateway usage metering (DS-002)

Metering is opt-in per registered OpenAI service via the private `/api/config` field
`usage_metering_profiles`, which maps each service ID to a profile. Updates that omit
the field preserve it. An empty map disables it. Drain changed services and cross a
minute boundary before changing the profile.

| Profile | Upstream behavior |
|---|---|
| `vllm-0.19.1-prompt-details` | Original final-only profile. Use it for a route that reports final usage in JSON or an SSE usage-only event. |
| `vllm-0.19.1-per-choice` | vLLM 0.19.1 choice-scoped progress, including through SMG HTTP when the worker forces usage. Older SMG HTTP can drop the per-request continuous option. |
| `dynamo-1.6.2-rust` | Dynamo 1.6.2 default chat processor with request-wide progress and a final usage-only event. |
| `dynamo-1.6.2-vllm` | Dynamo 1.6.2 Python vLLM chat processor with request-wide progress and usage on the finishing choice. |

The progress profiles request `continuous_usage_stats` privately. Streaming callers
who request usage receive one request-wide final SSE event when the Gateway has a
complete measurement. The collector books the authoritative final or the measured
prefix once in the minute the attempt closes. A prefix contributes to the measured
totals, and `unknown_usage_attempts` includes attempts with an unmeasured remainder.

The existing Python model proxy observes backend JSON/SSE usage and obtains a verified
user ID from server's additive `authorize_proxy` endpoint. Counters use that user ID
and the service ID. They describe measured usage, not a payer or a charge.

Gateway owns `/home/ubuntu/dstack/usage-counters.json` with an active minute and immutable
pending batches. Atomic checkpoints and exact-ID ACK protect closed data; active
observations since the last successful checkpoint can be lost on forced termination.
The `.lock` sidecar enforces one process, and `.initialized` detects missing established state.
Never delete/reset these files as a routine repair: reconcile identity/history first.

The `GatewayReplicaPipeline` worker holding the running replica's lease polls
`/api/usage/batches` over its private SSH management connection. It verifies the
source and lease token, commits the page's numbered `usage_batches` rows, then POSTs
`/api/usage/batches/ack` outside the transaction. If the server exits between
commit and ACK, another server can claim the replica after lease expiry and ACK
the replayed page after matching its full contents. Old Gateways lacking the usage API
still get normal state sync. For reports, aggregate the counter columns directly in
`usage_batches` by `user_id`, `run_id`, Gateway or minute. Each row represents one
user and run in a replica's batch.

On planned removal of a serving Gateway replica, the worker calls the private
`POST /api/usage/drain`. Nginx fences new public requests and lets open HTTP
streams and WebSockets finish. The collector then seals the final active minute.
The worker keeps delivering closed batches during the wait. Only a sealed, empty
queue permits the worker to mark the VM for termination. An open stream can
therefore delay scale-in. Update the Gateway and all server workers before
relying on this protocol. If a Gateway lacks the drain API or crashes with
unresolved requests, its VM stays in place pending upgrade or reconciliation.

Public project model endpoints traverse metering; direct service hostnames still bypass it.
Resolve that routing policy before paid use. Token quotas are outside DS-002. Local
scenarios live in `src/tests/_internal/proxy/gateway/metering`; real-minute and real-Nginx
checks are explicit opt-ins.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ addopts = [
asyncio_default_fixture_loop_scope = "session"
asyncio_default_test_loop_scope = "session"
markers = [
"metering_realtime: explicit actual-minute DS-002 acceptance run",
"shim_version",
"dockerized",
]
Expand Down
49 changes: 45 additions & 4 deletions src/dstack/_internal/proxy/gateway/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""FastAPI app running on a gateway."""

import asyncio
import contextlib
import time
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
Expand All @@ -24,12 +27,17 @@
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.stats import router as stats_router
from dstack._internal.proxy.gateway.routers.usage import router as usage_router
from dstack._internal.proxy.gateway.services.metering import Clock, MeteringCollector
from dstack._internal.proxy.gateway.services.metering_store import MeteringStore
from dstack._internal.proxy.gateway.services.nginx import Nginx
from dstack._internal.proxy.gateway.services.registry import ACCESS_LOG_PATH, apply_all
from dstack._internal.proxy.gateway.services.server_client import HTTPMultiClient
from dstack._internal.proxy.gateway.services.stats import StatsCollector
from dstack._internal.proxy.lib.errors import ProxyError
from dstack._internal.proxy.lib.routers.model_proxy import router as model_proxy_router
from dstack._internal.utils.common import run_async
from dstack._internal.utils.logging import get_logger
from dstack.version import __version__

STATE_FILE = DSTACK_DIR_ON_GATEWAY / "state-v2.json"
Expand All @@ -46,12 +54,27 @@ async def lifespan(app: FastAPI):
await run_async(nginx.write_global_conf)
await apply_all(repo, nginx, service_conn_pool)

yield
metering = injector.get_metering()
await metering.configure_profiles((await repo.get_config()).usage_metering_profiles)
maintenance = asyncio.create_task(_metering_maintenance(metering))
try:
yield
finally:
maintenance.cancel()
with contextlib.suppress(asyncio.CancelledError):
await maintenance
try:
await metering.close()
finally:
await service_conn_pool.remove_all()

await service_conn_pool.remove_all()


def make_app(repo: Optional[GatewayProxyRepo] = None, nginx: Optional[Nginx] = None) -> FastAPI:
def make_app(
repo: Optional[GatewayProxyRepo] = None,
nginx: Optional[Nginx] = None,
metering_store: MeteringStore | None = None,
clock: Clock | None = None,
) -> FastAPI:
if repo is None:
migrate_from_state_v1(
v1_file=LEGACY_STATE_FILE, v2_file=STATE_FILE, keys_dir=LEGACY_KEYS_DIR
Expand All @@ -66,6 +89,10 @@ def make_app(repo: Optional[GatewayProxyRepo] = None, nginx: Optional[Nginx] = N
),
nginx=nginx or Nginx(),
stats_collector=StatsCollector(ACCESS_LOG_PATH),
metering=MeteringCollector(
metering_store or MeteringStore(DSTACK_DIR_ON_GATEWAY / "usage-counters.json"),
clock=clock,
),
)

# TODO: add CORS only to openai routers once fastapi supports it.
Expand All @@ -83,9 +110,23 @@ def make_app(repo: Optional[GatewayProxyRepo] = None, nginx: Optional[Nginx] = N
app.include_router(registry_router, prefix="/api/registry")
app.include_router(services_router, prefix="/api/services")
app.include_router(stats_router, prefix="/api/stats")
app.include_router(usage_router, prefix="/api/usage")

@app.get("/")
def get_info():
return {"version": __version__}

return app


async def _metering_maintenance(metering: MeteringCollector) -> None:
last_checkpoint = time.monotonic()
while True:
await asyncio.sleep(1)
try:
await metering.rotate_if_due()
if time.monotonic() - last_checkpoint >= 60:
await metering.checkpoint()
last_checkpoint = time.monotonic()
except (OSError, ValueError, ProxyError):
get_logger(__name__).exception("Usage maintenance failed; metered admission paused")
32 changes: 31 additions & 1 deletion src/dstack/_internal/proxy/gateway/auth.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import uuid

import httpx2 as httpx
from aiocache import cached
from pydantic import ValidationError

from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider
from dstack._internal.proxy.lib.errors import UnexpectedProxyError
from dstack._internal.proxy.lib.schemas.usage import AuthorizedSubject

_AUTH_CACHE_TTL_SECONDS = 60
"""Seconds to cache allowed or denied access for each project/token pair."""
Expand All @@ -11,8 +15,13 @@
class GatewayProxyAuthProvider(BaseProxyAuthProvider):
def __init__(self, server_client: httpx.AsyncClient) -> None:
self._server_client = server_client
self._cache_namespace = uuid.uuid4().hex

@cached(ttl=_AUTH_CACHE_TTL_SECONDS, noself=True, skip_cache_func=lambda r: r is None)
@cached(
ttl=_AUTH_CACHE_TTL_SECONDS,
key_builder=lambda f, self, project, token: repr((self._cache_namespace, project, token)),
skip_cache_func=lambda r: r is None,
)
async def is_project_member(self, project_name: str, token: str) -> bool:
try:
resp = await self._server_client.post(
Expand All @@ -27,3 +36,24 @@ async def is_project_member(self, project_name: str, token: str) -> bool:
f"Failed requesting dstack-server to check access: {e!r}"
) from e
return True

async def resolve_subject(self, project_name: str, token: str) -> AuthorizedSubject | None:
return await self._resolve_subject(project_name, token)

@cached(
ttl=_AUTH_CACHE_TTL_SECONDS,
key_builder=lambda f, self, project, token: repr((self._cache_namespace, project, token)),
skip_cache_func=lambda result: result is None,
)
async def _resolve_subject(self, project_name: str, token: str) -> AuthorizedSubject | None:
try:
response = await self._server_client.post(
f"/api/projects/{project_name}/authorize_proxy",
headers={"Authorization": f"Bearer {token}"},
)
if response.status_code in (401, 403, 404, 405):
return None
response.raise_for_status()
return AuthorizedSubject.model_validate_json(response.content)
except (httpx.HTTPError, ValidationError) as exc:
raise UnexpectedProxyError("Failed to resolve verified proxy identity") from exc
19 changes: 19 additions & 0 deletions src/dstack/_internal/proxy/gateway/deps.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import asyncio
from typing import Annotated, AsyncGenerator

from fastapi import Depends, FastAPI, Request

from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo
from dstack._internal.proxy.gateway.services.metering import MeteringCollector
from dstack._internal.proxy.gateway.services.nginx import Nginx
from dstack._internal.proxy.gateway.services.stats import StatsCollector
from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider
Expand All @@ -22,19 +24,30 @@ def __init__(
auth: BaseProxyAuthProvider,
nginx: Nginx,
stats_collector: StatsCollector,
metering: MeteringCollector | None = None,
) -> None:
super().__init__()
self._repo = repo
self._auth = auth
self._nginx = nginx
self._stats_collector = stats_collector
self._metering = metering
self.config_lock = asyncio.Lock()

async def get_repo(self) -> AsyncGenerator[BaseProxyRepo, None]:
yield self._repo

async def get_auth_provider(self) -> AsyncGenerator[BaseProxyAuthProvider, None]:
yield self._auth

def get_usage_observer(self):
return self._metering or super().get_usage_observer()

def get_metering(self) -> MeteringCollector:
if self._metering is None:
raise UnexpectedProxyError("Gateway metering dependency is missing")
return self._metering

def get_nginx(self) -> Nginx:
return self._nginx

Expand Down Expand Up @@ -71,3 +84,9 @@ async def get_stats_collector(
injector: Annotated[GatewayDependencyInjector, Depends(get_gateway_injector)],
) -> StatsCollector:
return injector.get_stats_collector()


async def get_metering(
injector: Annotated[GatewayDependencyInjector, Depends(get_gateway_injector)],
) -> MeteringCollector:
return injector.get_metering()
4 changes: 3 additions & 1 deletion src/dstack/_internal/proxy/gateway/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

from typing import Optional

from pydantic import AnyHttpUrl
from pydantic import AnyHttpUrl, Field

from dstack._internal.proxy.lib.const import DEFAULT_SERVICE_READ_TIMEOUT
from dstack._internal.proxy.lib.models import ImmutableModel
from dstack._internal.proxy.lib.services.usage import MeteringProfile


class ModelEntrypoint(ImmutableModel):
Expand All @@ -23,3 +24,4 @@ class ACMESettings(ImmutableModel):

class GlobalProxyConfig(ImmutableModel):
acme_settings: ACMESettings = ACMESettings()
usage_metering_profiles: dict[str, MeteringProfile] = Field(default_factory=dict)
14 changes: 13 additions & 1 deletion src/dstack/_internal/proxy/gateway/resources/nginx/nginx.conf
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
user www-data;
worker_processes auto;
worker_processes {{ 1 if draining else "auto" }};
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

Expand Down Expand Up @@ -27,6 +27,18 @@ http {

gzip on;

{% if draining %}
# The model proxy forwards already accepted requests to services over 127.0.0.1.
allow 127.0.0.1;
deny all;
server {
listen unix:{{ drain_socket }};
return 200 "$pid";
}
include /etc/nginx/sites-enabled/00-log-format.conf;
include /etc/nginx/sites-enabled/443-*.conf;
{% else %}
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
{% endif %}
}
56 changes: 44 additions & 12 deletions src/dstack/_internal/proxy/gateway/routers/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@

from fastapi import APIRouter, Depends

from dstack._internal.proxy.gateway.deps import get_gateway_proxy_repo
from dstack._internal.proxy.gateway.models import ACMESettings, GlobalProxyConfig
from dstack._internal.proxy.gateway.deps import (
GatewayDependencyInjector,
get_gateway_injector,
get_gateway_proxy_repo,
get_metering,
)
from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo
from dstack._internal.proxy.gateway.schemas.common import OkResponse
from dstack._internal.proxy.gateway.schemas.config import ConfigRequest
from dstack._internal.proxy.gateway.services.metering import MeteringCollector
from dstack._internal.proxy.lib.errors import ProxyError
from dstack._internal.proxy.lib.models import OpenAIChatModelFormat

router = APIRouter()

Expand All @@ -15,14 +22,39 @@
async def update_global_config(
body: ConfigRequest,
repo: Annotated[GatewayProxyRepo, Depends(get_gateway_proxy_repo)],
metering: Annotated[MeteringCollector, Depends(get_metering)],
injector: Annotated[GatewayDependencyInjector, Depends(get_gateway_injector)],
) -> OkResponse:
await repo.set_config(
GlobalProxyConfig(
acme_settings=ACMESettings(
server=body.acme_server,
eab_kid=body.acme_eab_kid,
eab_hmac_key=body.acme_eab_hmac_key,
),
),
)
return OkResponse()
async with injector.config_lock:
config = await repo.get_config()
acme_changes = {
name.removeprefix("acme_"): getattr(body, name)
for name in body.model_fields_set
if name.startswith("acme_")
}
profiles = config.usage_metering_profiles
if "usage_metering_profiles" in body.model_fields_set:
if body.usage_metering_profiles is None:
raise ProxyError("Metering profiles must be an object; omit to preserve")
profiles = body.usage_metering_profiles
eligible = set()
for service in await repo.list_services():
for model in await repo.list_models(service.project_name):
if model.run_name == service.run_name and isinstance(
model.format_spec, OpenAIChatModelFormat
):
eligible.add(service.id)
if not profiles.keys() <= eligible:
raise ProxyError("Metering requires a registered OpenAI service with a stable ID")
updated = config.model_copy(
update={
"acme_settings": config.acme_settings.model_copy(update=acme_changes),
"usage_metering_profiles": profiles,
}
)

async def persist() -> None:
await repo.set_config(updated)

await metering.configure_profiles(profiles, persist=persist)
return OkResponse()
Loading