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
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Deploys Pathways service to a Kubernetes cluster using a JobSet template."""

from collections.abc import Callable, Sequence
from collections.abc import Callable, Mapping, Sequence
import dataclasses
import datetime
import logging
import math
import re
from typing import Any
from absl import app
from absl import flags
Expand Down Expand Up @@ -62,6 +63,23 @@
" Jobs have an effectively unlimited backoff limit.",
lower_bound=0,
)
_ANNOTATIONS = flags.DEFINE_multi_string(
"annotations",
[],
"Annotation to set on the JobSet, in the form KEY=VALUE. Repeat the flag"
" to set multiple annotations. The value may contain '=' and ','. For"
" example, to let a group manage the JobSet on clusters that enforce"
" ownership-based delete protection: --annotations="
"ownership.tpu.google.com/co-owners=group:my-team@twosync.google.com",
)
# Kubernetes annotation keys are qualified names: an optional DNS subdomain
# prefix followed by '/' and a name of at most 63 characters.
_ANNOTATION_KEY_NAME_RE = re.compile(
r"[A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?"
)
_ANNOTATION_KEY_PREFIX_RE = re.compile(
r"[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*"
)
_SIDECAR_SHM_DIR = "/tmp/sidecar_dir"
# These make the colocated Python sidecar logs as verbose as possible so that
# issues in the sidecar (e.g. array (de)serialization during checkpointing) can
Expand Down Expand Up @@ -209,6 +227,52 @@ def _add_sidecar(pw_jobset: jobset.PathwaysJobSet, sidecar_image: str) -> None:
)


def _validate_annotation_key(key: str) -> None:
"""Raises ValueError if `key` is not a valid Kubernetes annotation key."""
prefix, sep, name = key.rpartition("/")
if sep and (
len(prefix) > 253 or not _ANNOTATION_KEY_PREFIX_RE.fullmatch(prefix)
):
raise ValueError(
f"Invalid annotation key {key!r}: the prefix {prefix!r} must be a DNS"
" subdomain of at most 253 characters."
)
if len(name) > 63 or not _ANNOTATION_KEY_NAME_RE.fullmatch(name):
raise ValueError(
f"Invalid annotation key {key!r}: the name {name!r} must be at most 63"
" characters, start and end with an alphanumeric character, and"
" contain only alphanumerics, '-', '_' or '.'."
)


def parse_annotations(annotations: Sequence[str]) -> dict[str, str]:
"""Parses KEY=VALUE strings into a dict of JobSet annotations.

Args:
annotations: Strings of the form KEY=VALUE. The string is split at the first
'=', so the value may itself contain '='.

Returns:
A dict mapping annotation keys to values.

Raises:
ValueError: An entry is malformed, has an invalid key, or repeats a key.
"""
parsed = {}
for annotation in annotations:
key, sep, value = annotation.partition("=")
key = key.strip()
if not sep:
raise ValueError(
f"Invalid annotation {annotation!r}: expected the form KEY=VALUE."
)
_validate_annotation_key(key)
if key in parsed:
raise ValueError(f"Annotation {key!r} is specified more than once.")
parsed[key] = value
return parsed


def run_deployment(
*,
tpu_type,
Expand All @@ -221,8 +285,12 @@ def run_deployment(
dry_run,
deploy_func: Callable[[dict[str, Any]], None] = deploy_jobset,
max_restarts: int = 30,
annotations: Mapping[str, str] | None = None,
) -> None:
"""Executes the deployment logic."""
annotations = dict(annotations) if annotations else {}
if annotations:
_logger.info("Setting JobSet annotations: %s", annotations)
# Use PathwaysJobSet builder instead of YAML template.
pw_jobset = jobset.PathwaysJobSet(
name=jobset_name,
Expand All @@ -239,6 +307,7 @@ def run_deployment(
pathways_rm_and_worker_image=(
server_image or jobset.DEFAULT_PATHWAYS_RM_AND_WORKER_IMAGE
),
annotations=annotations,
)

if sidecar_image:
Expand Down Expand Up @@ -317,6 +386,7 @@ def main(argv: Sequence[str]) -> None:
sidecar_image=_SIDECAR_IMAGE.value,
dry_run=_DRY_RUN.value,
max_restarts=_MAX_RESTARTS.value,
annotations=parse_annotations(_ANNOTATIONS.value),
)
except ValueError as e:
_logger.exception("Error: %s", e)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ def test_run_deployment(self, mock_jobset_cls, mock_detect):
max_restarts=30,
max_slice_restarts=1000000,
pathways_rm_and_worker_image="custom-server-image",
annotations={},
)

# Verify colocated python was added with correct image, SHM path, and
Expand Down Expand Up @@ -174,6 +175,134 @@ def test_main_deploys_without_sidecar_by_default(self, mock_run_deployment):
mock_run_deployment.assert_called_once()
self.assertIsNone(mock_run_deployment.call_args.kwargs["sidecar_image"])

@mock.patch.object(deploy_pathways_service, "run_deployment", autospec=True)
def test_main_passes_annotations(self, mock_run_deployment):
with flagsaver.as_parsed(
annotations=[
(
"ownership.tpu.google.com/co-owners="
"group:team-a@twosync.google.com,user:someone@google.com"
),
"example.com/team=pathways",
]
):
deploy_pathways_service.main(["deploy_pathways_service"])

mock_run_deployment.assert_called_once()
self.assertEqual(
mock_run_deployment.call_args.kwargs["annotations"],
{
"ownership.tpu.google.com/co-owners": (
"group:team-a@twosync.google.com,user:someone@google.com"
),
"example.com/team": "pathways",
},
)

@mock.patch.object(deploy_pathways_service, "run_deployment", autospec=True)
def test_main_invalid_annotation_raises(self, mock_run_deployment):
with flagsaver.as_parsed(annotations=["no-equals-sign"]):
with self.assertRaisesRegex(ValueError, "KEY=VALUE"):
deploy_pathways_service.main(["deploy_pathways_service"])
mock_run_deployment.assert_not_called()

@parameterized.named_parameters(
dict(testcase_name="empty", annotations=[], expected={}),
dict(
testcase_name="prefixed_key",
annotations=["ownership.tpu.google.com/co-owners=group:a@x.com"],
expected={"ownership.tpu.google.com/co-owners": "group:a@x.com"},
),
dict(
testcase_name="unprefixed_key",
annotations=["owner=me"],
expected={"owner": "me"},
),
dict(
testcase_name="value_with_equals_and_commas",
annotations=["example.com/k=a=b,c=d"],
expected={"example.com/k": "a=b,c=d"},
),
dict(
testcase_name="empty_value",
annotations=["example.com/k="],
expected={"example.com/k": ""},
),
dict(
testcase_name="multiple",
annotations=["example.com/a=1", "example.com/b=2"],
expected={"example.com/a": "1", "example.com/b": "2"},
),
)
def test_parse_annotations_valid(self, annotations, expected):
self.assertEqual(
deploy_pathways_service.parse_annotations(annotations), expected
)

@parameterized.named_parameters(
dict(testcase_name="missing_equals", annotation="example.com/k"),
dict(testcase_name="empty_key", annotation="=value"),
dict(testcase_name="empty_name", annotation="example.com/=value"),
dict(testcase_name="invalid_name_char", annotation="example.com/a b=v"),
dict(testcase_name="name_too_long", annotation=f"{'a' * 64}=v"),
dict(testcase_name="uppercase_prefix", annotation="Example.com/k=v"),
dict(testcase_name="empty_prefix", annotation="/k=v"),
dict(testcase_name="prefix_too_long", annotation=f"{'a' * 254}/k=v"),
)
def test_parse_annotations_invalid(self, annotation):
with self.assertRaises(ValueError):
deploy_pathways_service.parse_annotations([annotation])

def test_parse_annotations_duplicate_key_raises(self):
with self.assertRaisesRegex(ValueError, "more than once"):
deploy_pathways_service.parse_annotations(
["example.com/k=1", "example.com/k=2"]
)

def _run_dry_run_deployment(self, **kwargs):
captured_config = {}

def capture_yaml_dump(config, *args, **unused_kwargs):
del args, unused_kwargs
captured_config.update(config)
return ""

with mock.patch.object(
deploy_pathways_service.yaml, "dump", side_effect=capture_yaml_dump
):
deploy_pathways_service.run_deployment(
tpu_type="v5e",
topology="4x8",
num_slices=2,
jobset_name="test-jobset",
gcs_bucket="gs://test-bucket",
server_image="server-image",
sidecar_image=None,
dry_run=True,
**kwargs,
)
return captured_config

def test_run_deployment_sets_annotations(self):
annotations = {
"ownership.tpu.google.com/co-owners": "group:a@x.com,group:b@x.com",
"example.com/team": "pathways",
}

captured_config = self._run_dry_run_deployment(annotations=annotations)

self.assertEqual(captured_config["metadata"]["annotations"], annotations)

@parameterized.named_parameters(
dict(testcase_name="default", kwargs={}),
dict(testcase_name="none", kwargs=dict(annotations=None)),
dict(testcase_name="empty", kwargs=dict(annotations={})),
)
def test_run_deployment_no_annotations_omits_annotations(self, kwargs):
captured_config = self._run_dry_run_deployment(**kwargs)

self.assertNotIn("annotations", captured_config["metadata"])

@mock.patch.object(gke_utils, "get_current_cluster_and_project")
def test_run_deployment_worker_backoff_limit(self, mock_detect):
mock_detect.return_value = ("test-cluster", "test-project")
Expand Down
Loading