mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-05 01:59:27 +00:00
* feat(proxy): offload spend tracking to a pod-local spend worker sidecar py-spy on the gateway showed the post-response _PROXY_track_cost_callback, spend-log and DBSpendUpdateWriter work running on the inference workers' event loop, so a DB or Redis stall backed up the request path. When LITELLM_SPEND_WORKER_ENABLED=true, _ProxyDBLogger serializes one compact typed SpendEvent per success and hands it to a SpendEventProducer that ships it over a unix socket (default) or loopback-only TCP to a sidecar started as `python -m gateway.spend_worker`. The sidecar runs the unchanged _ProxyDBLogger pipeline against the pod's PgBouncer (pooled_database_url). When the sidecar is unreachable, the buffer is full, or the gateway shuts down with events still queued or in flight, the producer applies LITELLM_SPEND_WORKER_ON_UNAVAILABLE (fallback in-process, or drop). The sidecar half-closes producers on SIGTERM and drains, the producer treats EOF as unavailable, and the gateway flushes buffered spend counters on shutdown. The sidecar honors LITELLM_LOG so its writes are visible in its own process log. Helm: both charts gain an opt-in spend-worker sidecar container sharing an emptyDir socket dir, and the componentized chart's HPA uses a ContainerResource CPU metric scoped to the gateway container so sidecar CPU does not drive inference scaling. * feat(terraform): opt-in spend-worker sidecar for the AWS and GCP gateway stacks Adds spend_worker_* inputs to both modules. On ECS Fargate the sidecar is a second, non-essential container in the gateway task; on Cloud Run it is a second container in the gateway service. Both listen on loopback TCP, share the gateway's DB/Redis/secret env, and set LITELLM_JOB_ROLE=spend_worker. Disabled by default. Plan-only tests cover both, and the terraform CI workflow now runs the gcp module too Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(proxy): retrieve a completed batch in the in-process spend path test The base now defers cost tracking for batches that are still in flight, so an in_progress batch never reaches update_database Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(proxy): rename the spend worker sidecar to collector Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): run the collector from the installed litellm package and finish in-flight fallbacks on shutdown The sidecar command becomes python -m litellm.proxy.collector so the classic image, whose runtime stage copies only the installed package, can run it. The module now assembles DATABASE_URL and the pod-local pgbouncer URL itself, replacing gateway/collector.py The componentized collector sidecar inherits gateway.volumeMounts so custom CA mounts reach it. SpendEventProducer shields an in-progress fallback from the writer task cancellation so close() no longer loses an event already handed to the in-process pipeline Helpers used across modules (address_argument, should_store_prompts_and_responses_in_spend_logs, flush_spend_counters_on_shutdown) become public so the change adds no reportPrivateUsage errors Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci(terraform): drop the gcp job duplicated by the aws/gcp matrix Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(collector): keep metrics env off the classic sidecar and reject shared loopback ports The classic chart no longer hands PROMETHEUS_METRICS_PORT and the billing metrics env to the collector container, and gives it the same /.npm scratch mount as the proxy on a read-only root. AWS and GCP now refuse a plan where the spend collector and the metrics sidecar bind the same loopback port. A regression test drives a sidecar crash mid-stream on asyncio and uvloop and checks no event is billed by both the sidecar and the in-process fallback; the producer docstring spells out why a failed drain() cannot double count Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * style(proxy): format pooled_database_url after the pgbouncer rebase Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): keep the cache-hit preset key and survive dead producers on collector drain Cache hits updated the logging object after the early return, so the offloaded spend event carried preset_cache_key=None and the collector re-hashed reconstructed kwargs. Also guard write_eof() against producer transports uvloop already closed so one dead connection cannot abort the drain Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(terraform): keep the gcp collector port off the metrics sidecar health port Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): collector connects to Postgres directly under IAM or Entra token auth Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): mark the collector's DATABASE_URL as pooled when it uses the pod's pgbouncer Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: yassin <yassin@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
763 lines
26 KiB
HCL
763 lines
26 KiB
HCL
# Three Cloud Run v2 services + one Cloud Run v2 job for migrations.
|
|
# All four use the same service account and the same VPC connector for
|
|
# private egress to Cloud SQL + Memorystore.
|
|
|
|
locals {
|
|
# Memorystore exposes a self-signed CA cert per instance; we ship it as
|
|
# a base64 env var and decode it to a file at container startup so the
|
|
# rediss:// connection can validate. Public cert, not sensitive.
|
|
redis_ca_pem_b64 = var.redis_transit_encryption ? base64encode(google_redis_instance.this.server_ca_certs[0].cert) : ""
|
|
|
|
shared_env_kv = concat(
|
|
[
|
|
{ name = "DATABASE_HOST", value = google_sql_database_instance.writer.private_ip_address },
|
|
{ name = "DATABASE_PORT", value = "5432" },
|
|
{ name = "DATABASE_USER", value = var.db_username },
|
|
{ name = "DATABASE_NAME", value = var.db_name },
|
|
{ name = "DATABASE_HOST_READ_REPLICA", value = google_sql_database_instance.reader.private_ip_address },
|
|
{ name = "DATABASE_PORT_READ_REPLICA", value = "5432" },
|
|
{ name = "REDIS_HOST", value = google_redis_instance.this.host },
|
|
{ name = "REDIS_PORT", value = tostring(google_redis_instance.this.port) },
|
|
],
|
|
var.redis_transit_encryption ? [
|
|
{ name = "REDIS_SSL", value = "true" },
|
|
{ name = "REDIS_SSL_CA_CERTS", value = "/tmp/redis-ca.pem" },
|
|
{ name = "REDIS_CA_PEM_B64", value = local.redis_ca_pem_b64 },
|
|
] : [],
|
|
[
|
|
{ name = "GCS_BUCKET_NAME", value = google_storage_bucket.this.name },
|
|
],
|
|
)
|
|
|
|
# OTel v2 is opt-in and gated on otel_endpoint, matching the AWS stack —
|
|
# nothing OTel-related is added to the container env until an endpoint is
|
|
# set. LITELLM_OTEL_V2 flips on alongside the OTEL_* block so the proxy
|
|
# never boots the instrumentation with no exporter wired in.
|
|
otel_enabled = var.otel_endpoint != ""
|
|
otel_environment_name = var.otel_environment_name != "" ? var.otel_environment_name : var.env
|
|
otel_shared_endpoint_kv = local.otel_enabled ? [
|
|
{ name = "LITELLM_OTEL_V2", value = "true" },
|
|
{ name = "OTEL_EXPORTER", value = var.otel_exporter },
|
|
{ name = "OTEL_ENDPOINT", value = var.otel_endpoint },
|
|
{ name = "OTEL_ENVIRONMENT_NAME", value = local.otel_environment_name },
|
|
{ name = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", value = var.otel_capture_message_content },
|
|
] : []
|
|
# OTel defaults are filtered out when the same key appears in
|
|
# *_extra_env, so a caller-supplied OTEL_SERVICE_NAME (or any other
|
|
# OTEL_*) takes precedence without colliding at Cloud Run apply time
|
|
# (Cloud Run rejects duplicate env var names).
|
|
gateway_otel_env_kv_raw = concat(local.otel_shared_endpoint_kv, local.otel_enabled ? [
|
|
{ name = "OTEL_SERVICE_NAME", value = "${local.name}-gateway" },
|
|
] : [])
|
|
backend_otel_env_kv_raw = concat(local.otel_shared_endpoint_kv, local.otel_enabled ? [
|
|
{ name = "OTEL_SERVICE_NAME", value = "${local.name}-backend" },
|
|
] : [])
|
|
gateway_otel_env_kv = [
|
|
for e in local.gateway_otel_env_kv_raw : e if !contains(keys(var.gateway_extra_env), e.name)
|
|
]
|
|
backend_otel_env_kv = [
|
|
for e in local.backend_otel_env_kv_raw : e if !contains(keys(var.backend_extra_env), e.name)
|
|
]
|
|
otel_env_secrets = local.otel_enabled && var.otel_headers_secret != "" ? [
|
|
{ name = "OTEL_HEADERS", secret = var.otel_headers_secret, version = "latest" },
|
|
] : []
|
|
|
|
# Enterprise request metering, gated on billing_metrics_endpoint. The
|
|
# endpoint rides in as a plain env var; the mTLS material lives in Secret
|
|
# Manager (secrets.tf) and is injected as PEM-valued env vars, which the
|
|
# proxy accepts in place of file paths. Each PEM is wired only when the
|
|
# operator supplied it, so an empty ca_cert_pem falls back to the system
|
|
# trust store.
|
|
billing_metrics_enabled = var.billing_metrics_endpoint != ""
|
|
billing_metrics_client_cert_enabled = local.billing_metrics_enabled && var.billing_metrics_client_cert_pem != ""
|
|
billing_metrics_client_key_enabled = local.billing_metrics_enabled && var.billing_metrics_client_key_pem != ""
|
|
billing_metrics_ca_cert_enabled = local.billing_metrics_enabled && var.billing_metrics_ca_cert_pem != ""
|
|
|
|
billing_metrics_env_kv = local.billing_metrics_enabled ? [
|
|
{ name = "LITELLM_BILLING_METRICS_ENDPOINT", value = var.billing_metrics_endpoint },
|
|
] : []
|
|
|
|
billing_metrics_env_secrets = concat(
|
|
local.billing_metrics_client_cert_enabled ? [
|
|
{ name = "LITELLM_BILLING_METRICS_CLIENT_CERT", secret = google_secret_manager_secret.billing_metrics_client_cert[0].id, version = "latest" },
|
|
] : [],
|
|
local.billing_metrics_client_key_enabled ? [
|
|
{ name = "LITELLM_BILLING_METRICS_CLIENT_KEY", secret = google_secret_manager_secret.billing_metrics_client_key[0].id, version = "latest" },
|
|
] : [],
|
|
local.billing_metrics_ca_cert_enabled ? [
|
|
{ name = "LITELLM_BILLING_METRICS_CA_CERT", secret = google_secret_manager_secret.billing_metrics_ca_cert[0].id, version = "latest" },
|
|
] : [],
|
|
)
|
|
|
|
# Cloud Run v2 secret env vars use value_source.secret_key_ref pointing at a
|
|
# secret resource ID. Shared between gateway and backend (the migrations
|
|
# job has its own narrower env list — see migrations_env_secrets below).
|
|
shared_env_secrets = concat(
|
|
[
|
|
{ name = "LITELLM_MASTER_KEY", secret = google_secret_manager_secret.master_key.id, version = "latest" },
|
|
{ name = "DATABASE_PASSWORD", secret = google_secret_manager_secret.db_password.id, version = "latest" },
|
|
],
|
|
var.litellm_license == "" ? [] : [
|
|
{ name = "LITELLM_LICENSE", secret = google_secret_manager_secret.license[0].id, version = "latest" },
|
|
],
|
|
)
|
|
|
|
# Backend-only managed secrets. UI_PASSWORD is consumed by the management
|
|
# API (UI login flow) and has no use on the gateway data plane.
|
|
backend_managed_env_secrets = var.ui_password == "" ? [] : [
|
|
{ name = "UI_PASSWORD", secret = google_secret_manager_secret.ui_password[0].id, version = "latest" },
|
|
]
|
|
|
|
# Per-component extras (from variables).
|
|
gateway_extra_env_kv = [
|
|
for k, v in var.gateway_extra_env : { name = k, value = v }
|
|
]
|
|
backend_extra_env_kv = [
|
|
for k, v in var.backend_extra_env : { name = k, value = v }
|
|
]
|
|
|
|
backend_default_env_kv = [
|
|
{ name = "STORE_MODEL_IN_DB", value = "true" },
|
|
]
|
|
gateway_extra_secret_kv = [
|
|
for k, v in var.gateway_extra_secrets : { name = k, secret = v, version = "latest" }
|
|
]
|
|
backend_extra_secret_kv = [
|
|
for k, v in var.backend_extra_secrets : { name = k, secret = v, version = "latest" }
|
|
]
|
|
|
|
# Decode the Memorystore CA cert (passed as REDIS_CA_PEM_B64) to the
|
|
# path REDIS_SSL_CA_CERTS points at, so the redis-py client can validate
|
|
# the rediss:// handshake.
|
|
redis_ca_fragment = var.redis_transit_encryption ? [
|
|
"python -c \"import os, base64, pathlib; pathlib.Path(os.environ['REDIS_SSL_CA_CERTS']).write_bytes(base64.b64decode(os.environ['REDIS_CA_PEM_B64']))\""
|
|
] : []
|
|
|
|
database_url_fragment = [
|
|
"export DATABASE_URL=\"postgresql://$${DATABASE_USER}:$${DATABASE_PASSWORD}@$${DATABASE_HOST}:$${DATABASE_PORT}/$${DATABASE_NAME}\"",
|
|
"export DATABASE_URL_READ_REPLICA=\"postgresql://$${DATABASE_USER}:$${DATABASE_PASSWORD}@$${DATABASE_HOST_READ_REPLICA}:$${DATABASE_PORT_READ_REPLICA}/$${DATABASE_NAME}\"",
|
|
]
|
|
|
|
gateway_pool_env = var.gateway_connection_pool_enabled ? [
|
|
{ name = "LITELLM_PGBOUNCER_ENABLED", value = "true" },
|
|
{ name = "LITELLM_PGBOUNCER_MAX_DB_CONNECTIONS", value = tostring(var.gateway_pool_max_db_connections) },
|
|
{ name = "LITELLM_PGBOUNCER_MAX_CLIENT_CONN", value = tostring(var.gateway_pool_max_client_conn) },
|
|
] : []
|
|
|
|
gateway_uvicorn_args = "--host 0.0.0.0 --port 4000 --workers ${var.gateway_num_workers}"
|
|
backend_uvicorn_args = "--host 0.0.0.0 --port 4001"
|
|
|
|
gateway_launch_cmd = "case \"$USE_DDTRACE\" in [Tt][Rr][Uu][Ee]) export DD_TRACE_OPENAI_ENABLED=\"False\"; exec ddtrace-run python -m gateway.launch ${local.gateway_uvicorn_args};; *) exec python -m gateway.launch ${local.gateway_uvicorn_args};; esac"
|
|
backend_launch_cmd = "case \"$USE_DDTRACE\" in [Tt][Rr][Uu][Ee]) export DD_TRACE_OPENAI_ENABLED=\"False\"; exec ddtrace-run uvicorn backend.main:app ${local.backend_uvicorn_args};; *) exec uvicorn backend.main:app ${local.backend_uvicorn_args};; esac"
|
|
|
|
gateway_args = join(" && ", concat(
|
|
local.redis_ca_fragment,
|
|
local.database_url_fragment,
|
|
[local.gateway_launch_cmd],
|
|
))
|
|
|
|
metrics_enabled = var.create_runtime && var.gateway_metrics_port != null
|
|
metrics_multiproc_dir = "/tmp/litellm_prometheus_multiproc"
|
|
metrics_volume = "prometheus-multiproc"
|
|
metrics_env_kv = local.metrics_enabled ? [{ name = "PROMETHEUS_MULTIPROC_DIR", value = local.metrics_multiproc_dir }] : []
|
|
metrics_config_volume = "gmp-config"
|
|
|
|
metrics_run_monitoring_yaml = local.metrics_enabled ? yamlencode({
|
|
apiVersion = "monitoring.googleapis.com/v1beta"
|
|
kind = "RunMonitoring"
|
|
metadata = { name = "${local.name}-gateway" }
|
|
spec = {
|
|
endpoints = [{ port = var.gateway_metrics_port, path = "/metrics", interval = "30s" }]
|
|
}
|
|
}) : ""
|
|
|
|
backend_args = join(" && ", concat(
|
|
local.redis_ca_fragment,
|
|
local.database_url_fragment,
|
|
[local.backend_launch_cmd],
|
|
))
|
|
|
|
collector_address = "tcp://127.0.0.1:${var.collector_port}"
|
|
collector_env_kv = var.collector_enabled ? [
|
|
{ name = "LITELLM_COLLECTOR_ENABLED", value = "true" },
|
|
{ name = "LITELLM_COLLECTOR_ADDRESS", value = local.collector_address },
|
|
{ name = "LITELLM_COLLECTOR_BUFFER_SIZE", value = tostring(var.collector_buffer_size) },
|
|
{ name = "LITELLM_COLLECTOR_ON_UNAVAILABLE", value = var.collector_on_unavailable },
|
|
{ name = "LITELLM_COLLECTOR_DRAIN_TIMEOUT_SECONDS", value = tostring(var.collector_drain_timeout_seconds) },
|
|
] : []
|
|
|
|
gateway_env_kv = concat(local.shared_env_kv, local.gateway_otel_env_kv, local.billing_metrics_env_kv, local.gateway_extra_env_kv, local.proxy_config_env, local.metrics_env_kv, local.gateway_pool_env, local.collector_env_kv)
|
|
gateway_env_secrets = concat(local.shared_env_secrets, local.otel_env_secrets, local.billing_metrics_env_secrets, local.gateway_extra_secret_kv)
|
|
|
|
collector_env_kv_all = concat(
|
|
local.shared_env_kv,
|
|
local.gateway_extra_env_kv,
|
|
local.proxy_config_env,
|
|
local.gateway_pool_env,
|
|
local.collector_env_kv,
|
|
[{ name = "LITELLM_JOB_ROLE", value = "collector" }],
|
|
)
|
|
collector_env_secrets = concat(local.shared_env_secrets, local.gateway_extra_secret_kv)
|
|
|
|
collector_args = join(" && ", concat(
|
|
local.redis_ca_fragment,
|
|
local.database_url_fragment,
|
|
["exec python -m litellm.proxy.collector"],
|
|
))
|
|
|
|
# Env shipped to the migrations Job. The migrations image runs run.py
|
|
# which assembles DATABASE_URL from these discrete vars itself, so we
|
|
# only need writer-side DB env (no read replica, no proxy_config, no
|
|
# master key).
|
|
migrations_env_kv = [
|
|
{ name = "DATABASE_HOST", value = google_sql_database_instance.writer.private_ip_address },
|
|
{ name = "DATABASE_PORT", value = "5432" },
|
|
{ name = "DATABASE_USER", value = var.db_username },
|
|
{ name = "DATABASE_NAME", value = var.db_name },
|
|
]
|
|
|
|
migrations_env_secrets = [
|
|
{ name = "DATABASE_PASSWORD", secret = google_secret_manager_secret.db_password.id, version = "latest" },
|
|
]
|
|
}
|
|
|
|
# ---------- Gateway ----------
|
|
resource "google_cloud_run_v2_service" "gateway" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
name = "${local.name}-gateway"
|
|
location = var.region
|
|
ingress = "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER"
|
|
labels = local.labels
|
|
deletion_protection = false
|
|
|
|
lifecycle {
|
|
precondition {
|
|
condition = !var.collector_enabled || var.gateway_metrics_port == null || var.collector_port != var.gateway_metrics_port
|
|
error_message = "collector_port and gateway_metrics_port must differ: both sidecars bind loopback in the same instance."
|
|
}
|
|
}
|
|
|
|
template {
|
|
service_account = google_service_account.runtime.email
|
|
max_instance_request_concurrency = var.gateway_max_instance_request_concurrency
|
|
|
|
vpc_access {
|
|
connector = google_vpc_access_connector.this[0].id
|
|
egress = "PRIVATE_RANGES_ONLY"
|
|
}
|
|
|
|
scaling {
|
|
min_instance_count = var.gateway_min_instances
|
|
max_instance_count = var.gateway_max_instances
|
|
}
|
|
|
|
containers {
|
|
name = "gateway"
|
|
image = local.gateway_image
|
|
command = ["sh", "-c"]
|
|
args = [local.gateway_args]
|
|
|
|
ports {
|
|
container_port = 4000
|
|
}
|
|
|
|
resources {
|
|
limits = {
|
|
cpu = var.gateway_cpu
|
|
memory = var.gateway_memory
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = local.gateway_env_kv
|
|
content {
|
|
name = env.value.name
|
|
value = env.value.value
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = local.gateway_env_secrets
|
|
content {
|
|
name = env.value.name
|
|
value_source {
|
|
secret_key_ref {
|
|
secret = env.value.secret
|
|
version = env.value.version
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "volume_mounts" {
|
|
for_each = local.proxy_config_enabled ? [1] : []
|
|
content {
|
|
name = local.proxy_config_volume
|
|
mount_path = local.proxy_config_mount_path
|
|
}
|
|
}
|
|
|
|
dynamic "volume_mounts" {
|
|
for_each = local.metrics_enabled ? [1] : []
|
|
content {
|
|
name = local.metrics_volume
|
|
mount_path = local.metrics_multiproc_dir
|
|
}
|
|
}
|
|
|
|
startup_probe {
|
|
http_get {
|
|
path = "/health/readiness"
|
|
port = 4000
|
|
}
|
|
initial_delay_seconds = 10
|
|
period_seconds = 10
|
|
timeout_seconds = 5
|
|
failure_threshold = 12
|
|
}
|
|
|
|
liveness_probe {
|
|
http_get {
|
|
path = "/health/liveliness"
|
|
port = 4000
|
|
}
|
|
period_seconds = 30
|
|
timeout_seconds = 5
|
|
}
|
|
}
|
|
|
|
dynamic "containers" {
|
|
for_each = local.metrics_enabled ? [1] : []
|
|
content {
|
|
name = "metrics"
|
|
image = local.gateway_image
|
|
command = ["python", "-m", "litellm.proxy.prometheus_metrics_server"]
|
|
args = ["--port", tostring(var.gateway_metrics_port)]
|
|
|
|
dynamic "env" {
|
|
for_each = local.metrics_env_kv
|
|
content {
|
|
name = env.value.name
|
|
value = env.value.value
|
|
}
|
|
}
|
|
|
|
volume_mounts {
|
|
name = local.metrics_volume
|
|
mount_path = local.metrics_multiproc_dir
|
|
}
|
|
|
|
startup_probe {
|
|
http_get {
|
|
path = "/health"
|
|
port = var.gateway_metrics_port
|
|
}
|
|
period_seconds = 5
|
|
timeout_seconds = 3
|
|
failure_threshold = 12
|
|
}
|
|
|
|
liveness_probe {
|
|
http_get {
|
|
path = "/health"
|
|
port = var.gateway_metrics_port
|
|
}
|
|
period_seconds = 30
|
|
timeout_seconds = 5
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "containers" {
|
|
for_each = local.metrics_enabled ? [1] : []
|
|
content {
|
|
name = "collector"
|
|
image = var.gateway_metrics_collector_image
|
|
depends_on = ["metrics"]
|
|
|
|
volume_mounts {
|
|
name = local.metrics_config_volume
|
|
mount_path = "/etc/rungmp"
|
|
}
|
|
|
|
liveness_probe {
|
|
http_get {
|
|
path = "/liveness"
|
|
port = 13133
|
|
}
|
|
period_seconds = 30
|
|
timeout_seconds = 30
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "containers" {
|
|
for_each = var.collector_enabled ? [1] : []
|
|
content {
|
|
name = "spend-collector"
|
|
image = local.gateway_image
|
|
command = ["sh", "-c"]
|
|
args = [local.collector_args]
|
|
|
|
resources {
|
|
limits = {
|
|
cpu = var.collector_cpu
|
|
memory = var.collector_memory
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = local.collector_env_kv_all
|
|
content {
|
|
name = env.value.name
|
|
value = env.value.value
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = local.collector_env_secrets
|
|
content {
|
|
name = env.value.name
|
|
value_source {
|
|
secret_key_ref {
|
|
secret = env.value.secret
|
|
version = env.value.version
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "volume_mounts" {
|
|
for_each = local.proxy_config_enabled ? [1] : []
|
|
content {
|
|
name = local.proxy_config_volume
|
|
mount_path = local.proxy_config_mount_path
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "volumes" {
|
|
for_each = local.proxy_config_enabled ? [1] : []
|
|
content {
|
|
name = local.proxy_config_volume
|
|
gcs {
|
|
bucket = google_storage_bucket.proxy_config[0].name
|
|
read_only = true
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "volumes" {
|
|
for_each = local.metrics_enabled ? [1] : []
|
|
content {
|
|
name = local.metrics_volume
|
|
empty_dir {
|
|
medium = "MEMORY"
|
|
size_limit = "256Mi"
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "volumes" {
|
|
for_each = local.metrics_enabled ? [1] : []
|
|
content {
|
|
name = local.metrics_config_volume
|
|
secret {
|
|
secret = google_secret_manager_secret.metrics_run_monitoring[0].secret_id
|
|
items {
|
|
version = "latest"
|
|
path = "config.yaml"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
depends_on = [
|
|
google_secret_manager_secret_iam_member.master_key,
|
|
google_secret_manager_secret_iam_member.db_password,
|
|
google_secret_manager_secret_iam_member.license,
|
|
google_secret_manager_secret_iam_member.extras,
|
|
google_secret_manager_secret_iam_member.otel_headers,
|
|
google_secret_manager_secret_iam_member.billing_metrics_client_cert,
|
|
google_secret_manager_secret_iam_member.billing_metrics_client_key,
|
|
google_secret_manager_secret_iam_member.billing_metrics_ca_cert,
|
|
google_secret_manager_secret_iam_member.metrics_run_monitoring,
|
|
google_project_iam_member.runtime_metric_writer,
|
|
google_storage_bucket_iam_member.proxy_config_runtime,
|
|
google_sql_user.app,
|
|
# Don't go live until the schema is migrated; otherwise the proxy boots,
|
|
# fails on missing tables, and Cloud Run keeps cold-restarting.
|
|
terraform_data.migration,
|
|
]
|
|
}
|
|
|
|
# ---------- Backend ----------
|
|
resource "google_cloud_run_v2_service" "backend" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
name = "${local.name}-backend"
|
|
location = var.region
|
|
ingress = "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER"
|
|
labels = local.labels
|
|
deletion_protection = false
|
|
|
|
template {
|
|
service_account = google_service_account.runtime.email
|
|
max_instance_request_concurrency = var.backend_max_instance_request_concurrency
|
|
|
|
vpc_access {
|
|
connector = google_vpc_access_connector.this[0].id
|
|
egress = "PRIVATE_RANGES_ONLY"
|
|
}
|
|
|
|
scaling {
|
|
min_instance_count = var.backend_min_instances
|
|
max_instance_count = var.backend_max_instances
|
|
}
|
|
|
|
containers {
|
|
image = local.backend_image
|
|
command = ["sh", "-c"]
|
|
args = [local.backend_args]
|
|
|
|
ports {
|
|
container_port = 4001
|
|
}
|
|
|
|
resources {
|
|
limits = {
|
|
cpu = var.backend_cpu
|
|
memory = var.backend_memory
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = concat(local.shared_env_kv, local.backend_default_env_kv, local.backend_otel_env_kv, local.billing_metrics_env_kv, local.backend_extra_env_kv, local.proxy_config_env, local.metrics_env_kv)
|
|
content {
|
|
name = env.value.name
|
|
value = env.value.value
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = concat(local.shared_env_secrets, local.backend_managed_env_secrets, local.otel_env_secrets, local.billing_metrics_env_secrets, local.backend_extra_secret_kv)
|
|
content {
|
|
name = env.value.name
|
|
value_source {
|
|
secret_key_ref {
|
|
secret = env.value.secret
|
|
version = env.value.version
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
dynamic "volume_mounts" {
|
|
for_each = local.proxy_config_enabled ? [1] : []
|
|
content {
|
|
name = local.proxy_config_volume
|
|
mount_path = local.proxy_config_mount_path
|
|
}
|
|
}
|
|
|
|
startup_probe {
|
|
http_get {
|
|
path = "/health/readiness"
|
|
port = 4001
|
|
}
|
|
initial_delay_seconds = 10
|
|
period_seconds = 10
|
|
timeout_seconds = 5
|
|
failure_threshold = 12
|
|
}
|
|
|
|
liveness_probe {
|
|
http_get {
|
|
path = "/health/liveliness"
|
|
port = 4001
|
|
}
|
|
period_seconds = 30
|
|
timeout_seconds = 5
|
|
}
|
|
}
|
|
|
|
dynamic "volumes" {
|
|
for_each = local.proxy_config_enabled ? [1] : []
|
|
content {
|
|
name = local.proxy_config_volume
|
|
gcs {
|
|
bucket = google_storage_bucket.proxy_config[0].name
|
|
read_only = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
depends_on = [
|
|
google_secret_manager_secret_iam_member.master_key,
|
|
google_secret_manager_secret_iam_member.db_password,
|
|
google_secret_manager_secret_iam_member.license,
|
|
google_secret_manager_secret_iam_member.ui_password,
|
|
google_secret_manager_secret_iam_member.extras,
|
|
google_secret_manager_secret_iam_member.otel_headers,
|
|
google_secret_manager_secret_iam_member.billing_metrics_client_cert,
|
|
google_secret_manager_secret_iam_member.billing_metrics_client_key,
|
|
google_secret_manager_secret_iam_member.billing_metrics_ca_cert,
|
|
google_storage_bucket_iam_member.proxy_config_runtime,
|
|
google_sql_user.app,
|
|
terraform_data.migration,
|
|
]
|
|
}
|
|
|
|
# ---------- UI ----------
|
|
# Static nginx — no DB, no Redis, no secrets. Runs as ui_runtime, a SA
|
|
# with zero IAM bindings, so a compromised UI container can't pivot to
|
|
# Secret Manager / Cloud SQL via the metadata service.
|
|
resource "google_cloud_run_v2_service" "ui" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
name = "${local.name}-ui"
|
|
location = var.region
|
|
ingress = "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER"
|
|
labels = local.labels
|
|
deletion_protection = false
|
|
|
|
template {
|
|
service_account = google_service_account.ui_runtime[0].email
|
|
max_instance_request_concurrency = var.ui_max_instance_request_concurrency
|
|
|
|
scaling {
|
|
min_instance_count = var.ui_min_instances
|
|
max_instance_count = var.ui_max_instances
|
|
}
|
|
|
|
containers {
|
|
image = local.ui_image
|
|
|
|
ports {
|
|
container_port = 3000
|
|
}
|
|
|
|
resources {
|
|
limits = {
|
|
cpu = var.ui_cpu
|
|
memory = var.ui_memory
|
|
}
|
|
}
|
|
|
|
startup_probe {
|
|
http_get {
|
|
path = "/healthz"
|
|
port = 3000
|
|
}
|
|
initial_delay_seconds = 5
|
|
period_seconds = 10
|
|
timeout_seconds = 3
|
|
failure_threshold = 6
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
# Allow the LB (any unauthenticated traffic from the configured serverless
|
|
# NEG) to invoke the Cloud Run services. The actual auth is in the proxy
|
|
# (LITELLM_MASTER_KEY); these IAM bindings just open up Cloud Run's invoker
|
|
# gate so the LB request makes it to the container.
|
|
resource "google_cloud_run_v2_service_iam_member" "gateway_allusers" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
project = var.project_id
|
|
location = google_cloud_run_v2_service.gateway[0].location
|
|
name = google_cloud_run_v2_service.gateway[0].name
|
|
role = "roles/run.invoker"
|
|
member = "allUsers"
|
|
}
|
|
|
|
resource "google_cloud_run_v2_service_iam_member" "backend_allusers" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
project = var.project_id
|
|
location = google_cloud_run_v2_service.backend[0].location
|
|
name = google_cloud_run_v2_service.backend[0].name
|
|
role = "roles/run.invoker"
|
|
member = "allUsers"
|
|
}
|
|
|
|
resource "google_cloud_run_v2_service_iam_member" "ui_allusers" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
project = var.project_id
|
|
location = google_cloud_run_v2_service.ui[0].location
|
|
name = google_cloud_run_v2_service.ui[0].name
|
|
role = "roles/run.invoker"
|
|
member = "allUsers"
|
|
}
|
|
|
|
# ---------- Migrations job ----------
|
|
# Dedicated litellm-migrations image — slim, ENTRYPOINT runs run.py which
|
|
# assembles DATABASE_URL from the DATABASE_* env vars and runs `prisma
|
|
# migrate deploy`. No proxy_config, no master key, no shell wrapper.
|
|
resource "google_cloud_run_v2_job" "migrations" {
|
|
count = var.create_runtime ? 1 : 0
|
|
|
|
name = "${local.name}-migrations"
|
|
location = var.region
|
|
labels = local.labels
|
|
deletion_protection = false
|
|
|
|
template {
|
|
template {
|
|
service_account = google_service_account.runtime.email
|
|
|
|
vpc_access {
|
|
connector = google_vpc_access_connector.this[0].id
|
|
egress = "PRIVATE_RANGES_ONLY"
|
|
}
|
|
|
|
containers {
|
|
image = local.migrations_image
|
|
|
|
# Prisma's Node + Rust engine plus the v2 migration resolver
|
|
# routinely peaks above 1 GiB while applying the schema, so 2 GiB
|
|
# is the floor — 1 GiB OOM-kills mid-migrate. CPU stays at 1 vCPU
|
|
# (Cloud Run requires >= 1 with concurrency > 1, and `prisma
|
|
# migrate deploy` is single-threaded so more buys nothing).
|
|
resources {
|
|
limits = {
|
|
cpu = "1000m"
|
|
memory = "4Gi"
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = local.migrations_env_kv
|
|
content {
|
|
name = env.value.name
|
|
value = env.value.value
|
|
}
|
|
}
|
|
|
|
dynamic "env" {
|
|
for_each = local.migrations_env_secrets
|
|
content {
|
|
name = env.value.name
|
|
value_source {
|
|
secret_key_ref {
|
|
secret = env.value.secret
|
|
version = env.value.version
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
depends_on = [
|
|
google_secret_manager_secret_iam_member.db_password,
|
|
google_sql_user.app,
|
|
]
|
|
}
|