docker_memory_check.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from __future__ import annotations
  2. import argparse
  3. import json
  4. import os.path
  5. import sys
  6. from collections.abc import Sequence
  7. def should_use_color(setting: str) -> bool:
  8. # normally I would use `sys.stdout.isatty()` however direnv always pipes this
  9. return setting == "always" or (setting == "auto" and not os.environ.get("CI"))
  10. def color(s: str, color: str, *, use_color: bool) -> str:
  11. if use_color:
  12. return f"{color}{s}\033[m"
  13. else:
  14. return s
  15. def main(argv: Sequence[str] | None = None) -> int:
  16. parser = argparse.ArgumentParser()
  17. parser.add_argument(
  18. "--settings-file",
  19. default=os.path.expanduser("~/Library/Group Containers/group.com.docker/settings.json"),
  20. help=argparse.SUPPRESS,
  21. )
  22. parser.add_argument(
  23. "--memory-minimum",
  24. default=8092,
  25. type=int,
  26. help="the minimum amount of allocated memory to warn for. default: %(default)s (MiB)",
  27. )
  28. parser.add_argument(
  29. "--color",
  30. choices=("always", "never", "auto"),
  31. default="auto",
  32. help="whether to use color. default: %(default)s (auto is determined by CI environment variable)",
  33. )
  34. args = parser.parse_args(argv)
  35. use_color = should_use_color(args.color)
  36. try:
  37. with open(args.settings_file) as f:
  38. contents = json.load(f)
  39. except (json.JSONDecodeError, OSError):
  40. return 0 # file didn't exist or was not json
  41. try:
  42. configured = contents["memoryMiB"]
  43. except KeyError:
  44. return 0 # configuration did not look like what we expected
  45. if not isinstance(configured, int):
  46. return 0 # configuration did not look like what we expected
  47. if configured < args.memory_minimum:
  48. msg = f"""\
  49. WARNING: docker is configured with less than the recommended minimum memory!
  50. - open Docker.app and adjust the memory in Settings -> Resources
  51. - current memory (MiB): {configured}
  52. - recommended minimum (MiB): {args.memory_minimum}
  53. """
  54. print(color(msg, "\033[33m", use_color=use_color), end="", file=sys.stderr)
  55. return 0
  56. if __name__ == "__main__":
  57. raise SystemExit(main())