You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import os
  17. import re
  18. def is_enabled(value: str) -> bool:
  19. return str(value).strip().lower() in {"1", "true", "yes", "on"}
  20. def env_setting_enabled(env_key: str, default: str = "false") -> bool:
  21. value = os.getenv(env_key, default)
  22. return is_enabled(value)
  23. def is_valid_memory_limit(mem: str | None) -> bool:
  24. """
  25. Return True if the input string is a valid Docker memory limit (e.g. '256m', '1g').
  26. Units allowed: b, k, m, g (case-insensitive).
  27. Disallows zero or negative values.
  28. """
  29. if not mem or not isinstance(mem, str):
  30. return False
  31. mem = mem.strip().lower()
  32. return re.fullmatch(r"[1-9]\d*(b|k|m|g)", mem) is not None
  33. def parse_timeout_duration(timeout: str | None, default_seconds: int = 10) -> int:
  34. """
  35. Parses a string like '90s', '2m', '1m30s' into total seconds (int).
  36. Supports 's', 'm' (lower or upper case). Returns default if invalid.
  37. '1m30s' -> 90
  38. """
  39. if not timeout or not isinstance(timeout, str):
  40. return default_seconds
  41. timeout = timeout.strip().lower()
  42. pattern = r"^(?:(\d+)m)?(?:(\d+)s)?$"
  43. match = re.fullmatch(pattern, timeout)
  44. if not match:
  45. return default_seconds
  46. minutes = int(match.group(1)) if match.group(1) else 0
  47. seconds = int(match.group(2)) if match.group(2) else 0
  48. total = minutes * 60 + seconds
  49. return total if total > 0 else default_seconds
  50. def format_timeout_duration(seconds: int) -> str:
  51. """
  52. Formats an integer number of seconds into a string like '1m30s'.
  53. 90 -> '1m30s'
  54. """
  55. if seconds < 60:
  56. return f"{seconds}s"
  57. minutes, sec = divmod(seconds, 60)
  58. if sec == 0:
  59. return f"{minutes}m"
  60. return f"{minutes}m{sec}s"