Skip to content

Commit d0dfb22

Browse files
authored
feat(kubernetes): export driver traces over OTLP (#2958)
Mirror the VM, Podman, and Docker driver tracing setup for Kubernetes. Export standalone driver spans through OTLP/gRPC as the distinct openshell-driver-kubernetes service, preserve gateway trace context, record lifecycle operations and gRPC failures, and flush spans on shutdown. Kubernetes currently runs in-process when selected as a built-in gateway driver. Use the temporary server-boundary shim shared with Podman and Docker so traces retain the shape they will have when Kubernetes moves to a separate process. Move the common ComputeDriver RPC tracing layer into openshell-otel to keep all drivers aligned. Propagate the active W3C context through the controller-reserved Sandbox annotation and enable Agent Sandbox OTLP export in the local k3s workflow. This connects asynchronous controller reconciliation spans to the originating OpenShell create trace. Expose gateway OTLP configuration through Helm and add an Aspire collector to the local k3s workflow. Extend helm:k3s:forward with OTLP ingest and trace UI forwarding for Kubernetes and local container gateway development. Signed-off-by: Kris Hicks <khicks@nvidia.com>
1 parent 572843b commit d0dfb22

29 files changed

Lines changed: 1280 additions & 307 deletions

File tree

‎.agents/skills/debug-openshell-cluster/SKILL.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -440,8 +440,12 @@ openshell gateway list
440440
openshell status
441441
```
442442

443-
A successful plaintext `helm:skaffold:run` registers and selects the local
444-
gateway; the forwarding task does not modify gateway metadata.
443+
The forwarding task always exposes the collector on ports `4317` and `18888`.
444+
It exposes the gateway on port `8090` only when the `openshell` Service exists,
445+
so collector-only Docker or Podman development remains valid before a Skaffold
446+
deployment. A successful plaintext `helm:skaffold:run` registers the local
447+
gateway and selects it as active; the forwarding task does not modify gateway
448+
metadata.
445449

446450
If the gateway is healthy but sandbox creation fails:
447451

‎.agents/skills/helm-dev-environment/SKILL.md‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,10 @@ mise run helm:k3s:create
2828
Creates a k3d cluster and merges its kubeconfig into the worktree-local `kubeconfig` file.
2929
Also applies the upstream agent-sandbox CRDs/controller (pinned via `AGENT_SANDBOX_VERSION`
3030
in `tasks/scripts/helm-k3s-local.sh`, fetched from `github.com/kubernetes-sigs/agent-sandbox`
31-
releases) and preloads the default community sandbox image into k3d so the first sandbox
32-
create does not wait on a large registry pull. Traefik is disabled at cluster creation time.
31+
releases), enables its OTLP tracing on v0.5 and later, installs an OTLP trace
32+
collector and UI in the `observability` namespace,
33+
and preloads the default community sandbox image into k3d so the first sandbox create
34+
does not wait on a large registry pull. Traefik is disabled at cluster creation time.
3335

3436
**Multi-worktree support:** the cluster name is derived from the last component of the
3537
current git branch (e.g. branch `kube-support/local-dev/tmutch` → cluster
@@ -47,6 +49,9 @@ Override with env vars before running `helm:k3s:create`:
4749
- `HELM_K3S_LB_HOST_PORT` (default: `8080`)
4850
- `HELM_K3S_PRELOAD_SANDBOX_IMAGE` (default:
4951
`ghcr.io/nvidia/openshell-community/sandboxes/base:latest`; set to an empty value to skip)
52+
- `HELM_K3S_COLLECTOR_IMAGE` (default:
53+
`mcr.microsoft.com/dotnet/aspire-dashboard:latest`)
54+
- `HELM_K3S_COLLECTOR_HEALTH_TIMEOUT` (default: `120` seconds)
5055

5156
### 2. Deploy OpenShell
5257

@@ -79,19 +84,42 @@ must be at least `1000` and distinct from the workload UID. The
7984
sidecar-mTLS profile reuses `ci/values-sidecar.yaml` and restores
8085
`server.disableTls=false` inline for Skaffold. The `pkiInitJob` hook (a pre-install
8186
Job that runs `openshell-gateway generate-certs`) generates mTLS secrets on first
82-
install. Envoy Gateway opt-in; see the Optional Add-ons section below.
87+
install. The default Skaffold values export gateway and Kubernetes-driver traces to
88+
the collector service installed by `helm:k3s:create`. Envoy Gateway opt-in; see the
89+
Optional Add-ons section below.
8390

8491
The gateway Service uses ClusterIP. Access is via Envoy Gateway (port `8080`) or
85-
the local forwarding task:
92+
the unified local forwarding task:
8693

8794
```bash
8895
mise run helm:k3s:forward
8996
```
9097

91-
The task forwards the Kubernetes gateway to `http://127.0.0.1:8090`. A
92-
successful plaintext `helm:skaffold:run` or `helm:skaffold:run:sidecar`
93-
registers and selects the gateway under the worktree-specific k3d cluster name.
94-
Keep the forwarding task running while using the endpoint.
98+
The task forwards OTLP/gRPC to `http://127.0.0.1:4317` and the trace UI to
99+
`http://127.0.0.1:18888`. When Skaffold has deployed a Kubernetes gateway, it
100+
also forwards the gateway to `http://127.0.0.1:8090`; otherwise it continues
101+
with the collector ports only. A successful plaintext `helm:skaffold:run` or
102+
`helm:skaffold:run:sidecar` registers the gateway under the worktree-specific
103+
k3d cluster name and selects it as the active gateway. Keep the forwarding
104+
task running while using those endpoints.
105+
106+
### Viewing local traces
107+
108+
The gateway exports OTLP/gRPC to
109+
`http://openshell-collector.observability.svc.cluster.local:4317` through the
110+
default Skaffold values. Forward OTLP/gRPC and the trace UI to the host:
111+
112+
```bash
113+
mise run helm:k3s:forward
114+
```
115+
116+
Open `http://127.0.0.1:18888` and exercise the gateway to inspect gateway and
117+
Kubernetes compute-driver spans under their distinct service names, along with
118+
Agent Sandbox controller reconciliation spans linked through the Sandbox
119+
trace-context annotation. The same command exposes OTLP/gRPC on
120+
`http://127.0.0.1:4317` and, when deployed, the Kubernetes gateway on
121+
`http://127.0.0.1:8090`; the local `gateway`, `gateway:docker`, and `gateway:vm`
122+
tasks export to the collector endpoint automatically.
95123

96124
**HA test deploy** (two gateway replicas + external PostgreSQL Secret): uncomment
97125
`#- ci/values-high-availability.yaml` in `deploy/helm/openshell/skaffold.yaml`,

‎Cargo.lock‎

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/openshell-driver-kubernetes/Cargo.toml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ path = "src/main.rs"
1616

1717
[dependencies]
1818
openshell-core = { path = "../openshell-core", default-features = false }
19+
openshell-otel = { path = "../openshell-otel" }
1920
openshell-policy = { path = "../openshell-policy" }
2021

2122
tokio = { workspace = true }
@@ -37,8 +38,15 @@ miette = { workspace = true }
3738
notify = "8"
3839

3940
[dev-dependencies]
41+
openshell-otel-test-support = { path = "../openshell-otel-test-support" }
42+
opentelemetry = { workspace = true }
43+
opentelemetry_sdk = { workspace = true, features = ["testing"] }
44+
bytes = { workspace = true }
45+
http = { workspace = true }
46+
http-body-util = { workspace = true }
4047
temp-env = "0.3"
4148
toml = { workspace = true }
49+
tower = { workspace = true }
4250

4351
[lints]
4452
workspace = true

‎crates/openshell-driver-kubernetes/README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@ workspace namespace modes via `workspace_mode`:
1919
gateway state; it never deletes or otherwise accesses the operator-managed
2020
Kubernetes namespace.
2121

22+
When the gateway configures `[openshell.gateway.otlp]`, Kubernetes
23+
compute-driver spans export to the same OTLP/gRPC collector with the service
24+
name `openshell-driver-kubernetes`. The driver preserves the gateway trace
25+
context and uses the same compute-driver RPC span names in its in-process and
26+
standalone forms.
27+
28+
When it creates an Agent Sandbox resource, the driver serializes the active W3C
29+
trace context into the controller-reserved `opentelemetry.io/trace-context`
30+
annotation. An OTLP-enabled Agent Sandbox controller can therefore attach its
31+
asynchronous reconciliation spans to the originating OpenShell create trace.
32+
2233
Workspace namespace modes assume exclusive control of the sandbox identity
2334
resource chain. In shared and managed modes, only the gateway and its trusted
2435
Agent Sandbox controller may administer the sandbox namespace, Sandbox CRs,

‎crates/openshell-driver-kubernetes/src/driver.rs‎

Lines changed: 157 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ pub type WatchStream =
6262
Pin<Box<dyn Stream<Item = Result<WatchSandboxesEvent, KubernetesDriverError>> + Send>>;
6363

6464
const MANAGED_SSH_NETWORK_POLICY_NAME: &str = "openshell-sandbox-ssh";
65+
const AGENT_SANDBOX_TRACE_CONTEXT_ANNOTATION: &str = "opentelemetry.io/trace-context";
6566

6667
#[derive(Debug, thiserror::Error)]
6768
pub enum KubernetesDriverError {
@@ -467,6 +468,23 @@ impl std::fmt::Debug for KubernetesComputeDriver {
467468
}
468469

469470
impl KubernetesComputeDriver {
471+
#[cfg(test)]
472+
pub(crate) fn new_for_test(config: KubernetesComputeConfig) -> Self {
473+
let service = tower::service_fn(|_request: http::Request<kube::client::Body>| async {
474+
Ok::<_, std::convert::Infallible>(http::Response::new(http_body_util::Empty::<
475+
bytes::Bytes,
476+
>::new()))
477+
});
478+
let client = Client::new(service, "default");
479+
Self {
480+
client: client.clone(),
481+
watch_client: client,
482+
sandbox_api_version: Arc::new(OnceCell::new()),
483+
config,
484+
operator_allowlist: None,
485+
}
486+
}
487+
470488
pub async fn new(
471489
config: KubernetesComputeConfig,
472490
shutdown_rx: tokio::sync::watch::Receiver<bool>,
@@ -1339,7 +1357,24 @@ impl KubernetesComputeDriver {
13391357
}
13401358

13411359
#[allow(clippy::similar_names)]
1360+
#[tracing::instrument(
1361+
name = "kubernetes.create_sandbox",
1362+
skip(self, sandbox),
1363+
fields(
1364+
otel.name = "kubernetes.create_sandbox",
1365+
otel.status_code = tracing::field::Empty,
1366+
sandbox.id = %sandbox.id,
1367+
sandbox.name = %sandbox.name,
1368+
)
1369+
)]
13421370
pub async fn create_sandbox(&self, sandbox: &Sandbox) -> Result<(), KubernetesDriverError> {
1371+
let span_status = openshell_otel::ErrorStatusGuard::current();
1372+
let result = self.create_sandbox_inner(sandbox).await;
1373+
span_status.finish(result)
1374+
}
1375+
1376+
#[allow(clippy::similar_names)]
1377+
async fn create_sandbox_inner(&self, sandbox: &Sandbox) -> Result<(), KubernetesDriverError> {
13431378
let gpu_requirements = sandbox
13441379
.spec
13451380
.as_ref()
@@ -1444,6 +1479,7 @@ impl KubernetesComputeDriver {
14441479
let kube_name = self.config.kube_resource_name(workspace, name);
14451480
let mut obj = DynamicObject::new(&kube_name, &agent_sandbox_api.resource);
14461481
let mut annotations = sandbox_annotations(sandbox);
1482+
add_trace_context_annotation(&mut annotations);
14471483
for key in [
14481484
crate::config::ANNOTATION_SCC_UID_RANGE,
14491485
crate::config::ANNOTATION_SCC_SUPPLEMENTAL_GROUPS,
@@ -1499,7 +1535,22 @@ impl KubernetesComputeDriver {
14991535
}
15001536
}
15011537

1538+
#[tracing::instrument(
1539+
name = "kubernetes.stop_sandbox",
1540+
skip(self),
1541+
fields(
1542+
otel.name = "kubernetes.stop_sandbox",
1543+
otel.status_code = tracing::field::Empty,
1544+
sandbox.id = %sandbox_id,
1545+
)
1546+
)]
15021547
pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> {
1548+
let span_status = openshell_otel::ErrorStatusGuard::current();
1549+
let result = self.stop_sandbox_inner(sandbox_id).await;
1550+
span_status.finish(result)
1551+
}
1552+
1553+
async fn stop_sandbox_inner(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> {
15031554
let (agent_sandbox_api, kube_name, pod_name, namespace, stop_timeout) = self
15041555
.patch_sandbox_operating_state(sandbox_id, false)
15051556
.await?;
@@ -1554,10 +1605,22 @@ impl KubernetesComputeDriver {
15541605
}
15551606
}
15561607

1608+
#[tracing::instrument(
1609+
name = "kubernetes.start_sandbox",
1610+
skip(self),
1611+
fields(
1612+
otel.name = "kubernetes.start_sandbox",
1613+
otel.status_code = tracing::field::Empty,
1614+
sandbox.id = %sandbox_id,
1615+
)
1616+
)]
15571617
pub async fn start_sandbox(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> {
1558-
self.patch_sandbox_operating_state(sandbox_id, true)
1618+
let span_status = openshell_otel::ErrorStatusGuard::current();
1619+
let result = self
1620+
.patch_sandbox_operating_state(sandbox_id, true)
15591621
.await
1560-
.map(|_| ())
1622+
.map(|_| ());
1623+
span_status.finish(result)
15611624
}
15621625

15631626
async fn patch_sandbox_operating_state(
@@ -1648,7 +1711,22 @@ impl KubernetesComputeDriver {
16481711
))
16491712
}
16501713

1714+
#[tracing::instrument(
1715+
name = "kubernetes.delete_sandbox",
1716+
skip(self),
1717+
fields(
1718+
otel.name = "kubernetes.delete_sandbox",
1719+
otel.status_code = tracing::field::Empty,
1720+
sandbox.id = %sandbox_id,
1721+
)
1722+
)]
16511723
pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result<bool, String> {
1724+
let span_status = openshell_otel::ErrorStatusGuard::current();
1725+
let result = self.delete_sandbox_inner(sandbox_id).await;
1726+
span_status.finish(result)
1727+
}
1728+
1729+
async fn delete_sandbox_inner(&self, sandbox_id: &str) -> Result<bool, String> {
16521730
info!(
16531731
sandbox_id = %sandbox_id,
16541732
workspace_mode = %self.config.workspace_mode,
@@ -1968,6 +2046,15 @@ impl KubernetesComputeDriver {
19682046
}
19692047
}
19702048

2049+
fn add_trace_context_annotation(annotations: &mut BTreeMap<String, String>) {
2050+
let Some(carrier) = openshell_otel::current_trace_context_carrier() else {
2051+
return;
2052+
};
2053+
if let Ok(value) = serde_json::to_string(&carrier) {
2054+
annotations.insert(AGENT_SANDBOX_TRACE_CONTEXT_ANNOTATION.to_string(), value);
2055+
}
2056+
}
2057+
19712058
fn should_try_next_sandbox_api_version(err: &KubeError) -> bool {
19722059
// Kubernetes returns a structured 404 for some missing API resources and a
19732060
// raw "404 page not found" body for others. Both mean the probed
@@ -4561,6 +4648,74 @@ mod tests {
45614648
static ENV_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
45624649
std::sync::LazyLock::new(|| std::sync::Mutex::new(()));
45634650

4651+
#[tokio::test]
4652+
async fn tracing_create_sandbox_failure_exports_a_kubernetes_operation_span() {
4653+
use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider};
4654+
use tracing::instrument::WithSubscriber as _;
4655+
use tracing_subscriber::layer::SubscriberExt as _;
4656+
4657+
let _tracing_lock = crate::otel_tracing::test_lock().await;
4658+
let exporter = InMemorySpanExporterBuilder::new().build();
4659+
let provider = SdkTracerProvider::builder()
4660+
.with_simple_exporter(exporter.clone())
4661+
.build();
4662+
let subscriber = tracing_subscriber::registry().with(crate::otel_tracing::layer(&provider));
4663+
let driver = KubernetesComputeDriver::new_for_test(KubernetesComputeConfig::default());
4664+
4665+
driver
4666+
.create_sandbox(&Sandbox::default())
4667+
.with_subscriber(subscriber)
4668+
.await
4669+
.expect_err("missing sandbox name should fail");
4670+
provider.force_flush().unwrap();
4671+
4672+
let spans = exporter.get_finished_spans().unwrap();
4673+
let span = spans
4674+
.iter()
4675+
.find(|span| span.name == "kubernetes.create_sandbox")
4676+
.expect("create operation span");
4677+
assert!(matches!(
4678+
span.status,
4679+
opentelemetry::trace::Status::Error { .. }
4680+
));
4681+
provider.shutdown().unwrap();
4682+
}
4683+
4684+
#[tokio::test]
4685+
async fn sandbox_annotation_propagates_the_active_w3c_trace_context() {
4686+
use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider};
4687+
use tracing_subscriber::layer::SubscriberExt as _;
4688+
4689+
let _tracing_lock = crate::otel_tracing::test_lock().await;
4690+
let exporter = InMemorySpanExporterBuilder::new().build();
4691+
let provider = SdkTracerProvider::builder()
4692+
.with_simple_exporter(exporter)
4693+
.build();
4694+
let subscriber = tracing_subscriber::registry().with(crate::otel_tracing::layer(&provider));
4695+
4696+
let annotations = tracing::subscriber::with_default(subscriber, || {
4697+
let span = tracing::info_span!("kubernetes.create_sandbox");
4698+
let _entered = span.enter();
4699+
let mut annotations = BTreeMap::new();
4700+
add_trace_context_annotation(&mut annotations);
4701+
annotations
4702+
});
4703+
4704+
let carrier: serde_json::Value = serde_json::from_str(
4705+
annotations
4706+
.get("opentelemetry.io/trace-context")
4707+
.expect("agent-sandbox trace-context annotation"),
4708+
)
4709+
.expect("annotation should contain a JSON propagation carrier");
4710+
let traceparent = carrier["traceparent"]
4711+
.as_str()
4712+
.expect("carrier should contain traceparent");
4713+
assert!(traceparent.starts_with("00-"));
4714+
assert_eq!(traceparent.len(), 55);
4715+
4716+
provider.shutdown().unwrap();
4717+
}
4718+
45644719
fn json_struct(value: serde_json::Value) -> Struct {
45654720
let serde_json::Value::Object(object) = value else {
45664721
panic!("expected JSON object");

0 commit comments

Comments
 (0)