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
3 changes: 2 additions & 1 deletion kubernetes/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from .create_from_yaml import (FailToCreateError, create_from_dict,
create_from_yaml, create_from_directory)
from .quantity import parse_quantity
from .duration import parse_duration
from .duration import Duration, parse_duration
from .metrics import (get_nodes_metrics, get_pods_metrics,
get_pods_metrics_in_all_namespaces)
from .retry import (Backoff, DEFAULT_BACKOFF, DEFAULT_RETRY,
Expand All @@ -34,6 +34,7 @@
"create_from_directory",
"parse_quantity",
"parse_duration",
"Duration",
"get_nodes_metrics",
"get_pods_metrics",
"get_pods_metrics_in_all_namespaces",
Expand Down
59 changes: 57 additions & 2 deletions kubernetes/utils/duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import List
from typing import Annotated, Any, List

import datetime
import re

import durationpy
from pydantic import AfterValidator, BeforeValidator, PlainSerializer

# Initialize our RE statically, rather than compiling for every call. This has
# the downside that it'll get compiled at import time but that shouldn't
Expand All @@ -27,8 +28,12 @@
# milliseconds.
maxDuration_ms = (((99999 * 3600) + (59 * 60) + 59) * 1_000) + 999

# Go's time.Duration format and range.
reGoDuration = re.compile(r'[-+]?(0|(([0-9]+\.?[0-9]*|\.[0-9]+)(ns|us|\u00b5s|\u03bcs|ms|s|m|h))+)')
maxGoDuration = datetime.timedelta(microseconds=(2 ** 63 - 1) // 1000)

def parse_duration(duration) -> datetime.timedelta:

def parse_duration(duration: str) -> datetime.timedelta:
"""
Parse GEP-2257 Duration format to a datetime.timedelta object.

Expand Down Expand Up @@ -172,3 +177,53 @@ def format_duration(delta: datetime.timedelta) -> str:
output.append(f"{delta_us // 1000}ms")

return "".join(output)


def _parse_go_duration(value: Any) -> Any:
if not isinstance(value, str):
return value
if not reGoDuration.fullmatch(value):
raise ValueError("Invalid duration format: {}".format(value))
return durationpy.from_str(value)


def _check_go_duration_range(value: datetime.timedelta) -> datetime.timedelta:
if abs(value) > maxGoDuration:
raise ValueError("Duration out of range: {}".format(value))
return value


def _decimal(value: int, digits: int) -> str:
whole, frac = divmod(value, 10 ** digits)
if not frac:
return str(whole)
return "{}.{}".format(whole, str(frac).zfill(digits).rstrip("0"))


def _format_go_duration(value: datetime.timedelta) -> str:
sign = "-" if value < datetime.timedelta(0) else ""
us = abs(value) // datetime.timedelta(microseconds=1)
if us == 0:
return "0s"
if us < 1000:
return "{}{}us".format(sign, us)
if us < 1_000_000:
return "{}{}ms".format(sign, _decimal(us, 3))

hours, us = divmod(us, 3_600_000_000)
minutes, us = divmod(us, 60_000_000)
seconds = _decimal(us, 6)
if hours:
return "{}{}h{}m{}s".format(sign, hours, minutes, seconds)
if minutes:
return "{}{}m{}s".format(sign, minutes, seconds)
return "{}{}s".format(sign, seconds)


# metav1.Duration for pydantic models
Duration = Annotated[
datetime.timedelta,
BeforeValidator(_parse_go_duration),
AfterValidator(_check_go_duration_range),
PlainSerializer(_format_go_duration, return_type=str),
]
94 changes: 94 additions & 0 deletions kubernetes/utils/duration_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Copyright 2026 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import unittest

from pydantic import BaseModel, ValidationError

from kubernetes.client import ApiClient
from kubernetes.utils import Duration


class Spec(BaseModel):
ttl: Duration


class DurationTest(unittest.TestCase):

def test_parses_go_durations(self):
cases = {
"720h0m0s": datetime.timedelta(hours=720),
"1h30m": datetime.timedelta(minutes=90),
"1.5s": datetime.timedelta(seconds=1.5),
"500ms": datetime.timedelta(milliseconds=500),
"1us": datetime.timedelta(microseconds=1),
"1\u00b5s": datetime.timedelta(microseconds=1),
".5s": datetime.timedelta(milliseconds=500),
"+5s": datetime.timedelta(seconds=5),
"0": datetime.timedelta(0),
"0s": datetime.timedelta(0),
"-1h": datetime.timedelta(hours=-1),
}
for value, expected in cases.items():
with self.subTest(value=value):
self.assertEqual(expected, Spec(ttl=value).ttl)

def test_accepts_timedelta(self):
ttl = datetime.timedelta(minutes=5)
self.assertEqual(ttl, Spec(ttl=ttl).ttl)

def test_dumps_go_durations(self):
cases = {
datetime.timedelta(hours=720): "720h0m0s",
datetime.timedelta(hours=10 ** 6): "1000000h0m0s",
datetime.timedelta(minutes=90): "1h30m0s",
datetime.timedelta(seconds=90): "1m30s",
datetime.timedelta(seconds=1.5): "1.5s",
datetime.timedelta(seconds=59, microseconds=123456): "59.123456s",
datetime.timedelta(minutes=10, microseconds=1): "10m0.000001s",
datetime.timedelta(milliseconds=1.5): "1.5ms",
datetime.timedelta(microseconds=1): "1us",
datetime.timedelta(minutes=-90): "-1h30m0s",
datetime.timedelta(0): "0s",
}
for ttl, expected in cases.items():
with self.subTest(ttl=ttl):
self.assertEqual({"ttl": expected}, Spec(ttl=ttl).model_dump())
self.assertEqual('{"ttl":"%s"}' % expected,
Spec(ttl=ttl).model_dump_json())

def test_json_round_trip(self):
spec = Spec(ttl="2m30.5s")
self.assertEqual(spec, Spec.model_validate_json(spec.model_dump_json()))

def test_rejects_invalid_durations(self):
for value in ["abc", "1", "1x", "", "1d", "1h 2m", "1h-2m", "2562048h",
"\u0661s"]:
with self.subTest(value=value):
with self.assertRaises(ValidationError):
Spec(ttl=value)

def test_rejects_out_of_range_timedelta(self):
with self.assertRaises(ValidationError):
Spec(ttl=datetime.timedelta(hours=2562048))

def test_dumped_model_is_a_valid_request_body(self):
body = ApiClient().sanitize_for_serialization(
Spec(ttl="720h0m0s").model_dump())
self.assertEqual({"ttl": "720h0m0s"}, body)


if __name__ == '__main__':
unittest.main()