Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions pathwaysutils/experimental/gke/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ pw_jobset = jobset.PathwaysJobSet(
### Heterogeneous Multi-Topology Slices
Combine multiple TPU slice topologies as separate worker `replicatedJobs`
within a single `JobSet`. Call `add_worker_topology` before worker mutators
(`add_colocated_python`, `add_gcsfuse`, or `with_custom_libtpu`) so they apply
across all worker templates:
(`add_colocated_python`, `add_gcsfuse`, `with_custom_libtpu`, or
`with_metrics`) so they apply across all worker templates:

```python
pw_jobset = (
Expand Down Expand Up @@ -115,6 +115,18 @@ pw_jobset.with_custom_libtpu(
)
```

### Pathways Metrics
Push the Pathways metrics whose public names match an RE2 regular expression
from the Pathways containers to an OpenTelemetry collector over OTLP/gRPC. By
default, they go to the Google-Built OpenTelemetry Collector at
`opentelemetry-collector.opentelemetry.svc.cluster.local:4317`, which writes
them to Cloud Monitoring; pass `endpoint` for another collector. Requires
Pathways images that support `--metrics_regex`:

```python
pw_jobset.with_metrics(metrics_regex="compilation|chip_seconds|errors")
```

### Container & Pod Spec Overrides
Customize arguments, environment variables, resources, or volumes on any container or pod:

Expand Down
107 changes: 106 additions & 1 deletion pathwaysutils/experimental/gke/jobset.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,7 +881,8 @@ def add_worker_topology(
"""Adds an additional worker TPU slice topology as a replicatedJob.

Call before worker mutators such as `add_gcsfuse`, `add_external_sidecar`,
or `with_custom_libtpu` so they apply across all worker templates.
`with_custom_libtpu`, or `with_metrics` so they apply across all worker
templates.

Args:
tpu_type: TPU type (e.g., "v5e" or "ct5lp-hightpu-8t").
Expand Down Expand Up @@ -1422,6 +1423,110 @@ def with_custom_libtpu(

return self

def with_metrics(
self,
metrics_regex: str,
endpoint: str | None = None,
containers: str | Sequence[str] = "all",
) -> "PathwaysJobSet":
"""Exports Pathways metrics to an OpenTelemetry collector.

Sets `--metrics_regex` on the selected Pathways containers, which then push
the Pathways metrics whose public names (e.g.,
`pathways_pipe_message_latency_milliseconds`) contain a match of the RE2
regular expression over OTLP/gRPC. By default, they push them to the
Google-Built OpenTelemetry Collector at
`http://opentelemetry-collector.opentelemetry.svc.cluster.local:4317`, which
writes them to Cloud Monitoring. Also sets environment variables that
identify where the metrics come from: `OTEL_SERVICE_NAME` to the container
name, and `OTEL_RESOURCE_ATTRIBUTES` to the pod name and UID, through
`K8S_POD_NAME` and `K8S_POD_UID`. Replaces previous values of the flag and
of these variables. Requires Pathways images that support `--metrics_regex`.

Args:
metrics_regex: RE2 regular expression that selects the metrics to export
(e.g., `"compilation|chip_seconds|errors"`, or `"."` for all of them).
endpoint: Optional OTLP endpoint of another collector, an `http://` or
`https://` URL (e.g., `"http://my-collector.monitoring:4317"`). Sets
`OTEL_EXPORTER_OTLP_ENDPOINT`.
containers: Target container selector (e.g. `"all"` or `"worker"`).

Returns:
Self for method chaining.

Raises:
ValueError: If `metrics_regex` is empty or `endpoint` is not an `http://`
or `https://` URL.
"""
if not metrics_regex:
raise ValueError("metrics_regex must not be empty.")
if endpoint is not None and not endpoint.lower().startswith(
("http://", "https://")
):
raise ValueError(
f"endpoint must be an http:// or https:// URL (got {endpoint!r})."
)

target_containers: str | Sequence[str] = (
("pathways-rm", "pathways-proxy", "pathways-worker")
if containers == "all"
else containers
)

for job_template in (self._head_job_template, *self.worker_job_templates):
pod_spec = job_template.spec.template.spec
all_containers = (pod_spec.containers or []) + (
pod_spec.init_containers or []
)
for container in self._filter_matching_containers(
target_containers, all_containers
):
container.args = [
arg
for arg in container.args or []
if not arg.startswith("--metrics_regex=")
] + [f"--metrics_regex={metrics_regex}"]

# Kubernetes expands $(K8S_POD_NAME) and $(K8S_POD_UID) only in the
# variables after them, so these are appended in this order.
metrics_env = [
client.V1EnvVar(name="OTEL_SERVICE_NAME", value=container.name),
client.V1EnvVar(
name="K8S_POD_NAME",
value_from=client.V1EnvVarSource(
field_ref=client.V1ObjectFieldSelector(
field_path="metadata.name"
)
),
),
client.V1EnvVar(
name="K8S_POD_UID",
value_from=client.V1EnvVarSource(
field_ref=client.V1ObjectFieldSelector(
field_path="metadata.uid"
)
),
),
client.V1EnvVar(
name="OTEL_RESOURCE_ATTRIBUTES",
value="k8s.pod.name=$(K8S_POD_NAME),k8s.pod.uid=$(K8S_POD_UID)",
),
]
if endpoint is not None:
metrics_env.append(
client.V1EnvVar(
name="OTEL_EXPORTER_OTLP_ENDPOINT", value=endpoint
)
)
metrics_env_names = {var.name for var in metrics_env}
container.env = [
var
for var in container.env or []
if var.name not in metrics_env_names
] + metrics_env

return self

def _compile_config(self) -> dict[str, Any]:
"""Compiles the JobSet configuration into a dictionary."""
job_names = _worker_job_names(self._worker_jobs)
Expand Down
174 changes: 174 additions & 0 deletions pathwaysutils/test/experimental/gke/jobset_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1922,6 +1922,180 @@ def test_with_custom_libtpu_all_skips_non_pathways_containers(self):
env_names = [e["name"] for e in container.get("env") or []]
self.assertNotIn("TPU_LIBRARY_PATH", env_names, non_pw_name)

def test_with_metrics(self):
pw_jobset = self._create_jobset(topology="2x2", num_slices=1)
returned = pw_jobset.with_metrics("compilation|chip_seconds")
self.assertIs(returned, pw_jobset)

helper = JobSetManifestHelper(pw_jobset.to_dict())
for container_name in ("pathways-rm", "pathways-proxy", "pathways-worker"):
matches = helper.get_all_containers_by_name(container_name)
self.assertLen(matches, 1, container_name)
_, container = matches[0]
self.assertEqual(
container["args"][-1], "--metrics_regex=compilation|chip_seconds"
)
# The pod variables come before OTEL_RESOURCE_ATTRIBUTES, which uses
# them.
self.assertEqual(
container["env"][-4:],
[
{"name": "OTEL_SERVICE_NAME", "value": container_name},
{
"name": "K8S_POD_NAME",
"valueFrom": {"fieldRef": {"fieldPath": "metadata.name"}},
},
{
"name": "K8S_POD_UID",
"valueFrom": {"fieldRef": {"fieldPath": "metadata.uid"}},
},
{
"name": "OTEL_RESOURCE_ATTRIBUTES",
"value": (
"k8s.pod.name=$(K8S_POD_NAME),k8s.pod.uid=$(K8S_POD_UID)"
),
},
],
container_name,
)
self.assertNotIn(
"OTEL_EXPORTER_OTLP_ENDPOINT", [e["name"] for e in container["env"]]
)

def test_with_metrics_replaces_previous_values(self):
pw_jobset = self._create_jobset(
topology="2x2",
num_slices=1,
worker_container_kwargs={
"args": ["--metrics_regex=old"],
"env": {"OTEL_SERVICE_NAME": "old", "OTEL_RESOURCE_ATTRIBUTES": ""},
},
)
pw_jobset.with_metrics("first", endpoint="http://first:4317")
pw_jobset.with_metrics("second", endpoint="https://second.example.com")

helper = JobSetManifestHelper(pw_jobset.to_dict())
for container_name in ("pathways-rm", "pathways-proxy", "pathways-worker"):
_, container = helper.get_all_containers_by_name(container_name)[0]
self.assertEqual(
[a for a in container["args"] if a.startswith("--metrics_regex=")],
["--metrics_regex=second"],
container_name,
)
env_names = [e["name"] for e in container["env"]]
self.assertLen(env_names, len(set(env_names)), container_name)
env = {e["name"]: e for e in container["env"]}
self.assertEqual(env["OTEL_SERVICE_NAME"]["value"], container_name)
self.assertEqual(
env["OTEL_EXPORTER_OTLP_ENDPOINT"]["value"],
"https://second.example.com",
)

def test_with_metrics_after_import(self):
pw_jobset = self._create_jobset(topology="2x2", num_slices=1)
pw_jobset.with_metrics("first")
temp_filepath = os.path.join(
self.create_tempdir().full_path, "jobset_metrics.yaml"
)
pw_jobset.export_yaml(temp_filepath)
imported = jobset.PathwaysJobSet.import_yaml(temp_filepath)
self.assertEqual(
normalize_k8s_spec(pw_jobset.to_dict()),
normalize_k8s_spec(imported.to_dict()),
)

imported.with_metrics("second")
helper = JobSetManifestHelper(imported.to_dict())
_, worker = helper.get_all_containers_by_name("pathways-worker")[0]
self.assertEqual(
[a for a in worker["args"] if a.startswith("--metrics_regex=")],
["--metrics_regex=second"],
)
env_names = [e["name"] for e in worker["env"]]
self.assertLen(env_names, len(set(env_names)))

@parameterized.named_parameters(
dict(
testcase_name="all",
containers="all",
selected=("pathways-rm", "pathways-proxy", "pathways-worker"),
),
dict(
testcase_name="worker",
containers="worker",
selected=("pathways-worker",),
),
dict(
testcase_name="names",
containers=["pathways-rm", "pathways-proxy"],
selected=("pathways-rm", "pathways-proxy"),
),
)
def test_with_metrics_selects_containers(self, containers, selected):
pw_jobset = self._create_jobset(topology="2x2", num_slices=1)
pw_jobset.add_colocated_python(
image="gcr.io/my-project/colocated-python:latest"
)
pw_jobset.add_user_workload(
image="us-docker.pkg.dev/my-project/test:v1",
command="python3 test.py",
)
pw_jobset.with_metrics(".", containers=containers)

helper = JobSetManifestHelper(pw_jobset.to_dict())
for container_name in (
"pathways-rm",
"pathways-proxy",
"pathways-worker",
"user-workload",
"colocated-python-sidecar",
):
matches = helper.get_all_containers_by_name(container_name)
self.assertLen(matches, 1, container_name)
_, container = matches[0]
env_names = [e["name"] for e in container.get("env") or []]
if container_name in selected:
self.assertIn("--metrics_regex=.", container["args"], container_name)
self.assertIn("OTEL_RESOURCE_ATTRIBUTES", env_names, container_name)
else:
self.assertNotIn(
"--metrics_regex=.", container.get("args") or [], container_name
)
self.assertNotIn("OTEL_RESOURCE_ATTRIBUTES", env_names, container_name)

def test_with_metrics_applies_to_all_worker_topologies(self):
pw_jobset = self._create_jobset(topology="4x8", num_slices=1)
pw_jobset.add_worker_topology(
tpu_type="ct5lp-hightpu-8t", topology="2x4", num_slices=1
).with_metrics(".")

helper = JobSetManifestHelper(pw_jobset.to_dict())
workers = helper.get_all_containers_by_name("pathways-worker")
self.assertLen(workers, 2)
for job_name, worker in workers:
self.assertIn("--metrics_regex=.", worker["args"], job_name)

@parameterized.named_parameters(
dict(
testcase_name="empty_regex",
metrics_regex="",
endpoint=None,
error="metrics_regex",
),
dict(
testcase_name="endpoint_without_scheme",
metrics_regex=".",
endpoint="collector:4317",
error="endpoint",
),
)
def test_with_metrics_rejects_invalid_arguments(
self, metrics_regex, endpoint, error
):
pw_jobset = self._create_jobset(topology="2x2", num_slices=1)
with self.assertRaisesRegex(ValueError, error):
pw_jobset.with_metrics(metrics_regex, endpoint=endpoint)

def test_add_gcsfuse_replaces_duplicate_mount_path(self):
pw_jobset = self._create_jobset(topology="2x2", num_slices=1)
pw_jobset.add_gcsfuse(
Expand Down
Loading