exists.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright Materialize, Inc. and contributors. All rights reserved.
  2. #
  3. # Use of this software is governed by the Business Source License
  4. # included in the LICENSE file at the root of this repository.
  5. #
  6. # As of the Change Date specified in that file, in accordance with
  7. # the Business Source License, use of this software will be governed
  8. # by the Apache License, Version 2.0.
  9. import subprocess
  10. from materialize import ui
  11. from materialize.cloudtest import DEFAULT_K8S_CONTEXT_NAME
  12. from materialize.ui import UIError
  13. def exists(
  14. resource: str,
  15. context: str = DEFAULT_K8S_CONTEXT_NAME,
  16. namespace: str | None = None,
  17. ) -> None:
  18. _exists(resource, True, context, namespace)
  19. def not_exists(
  20. resource: str,
  21. context: str = DEFAULT_K8S_CONTEXT_NAME,
  22. namespace: str | None = None,
  23. ) -> None:
  24. _exists(resource, False, context, namespace)
  25. def _exists(
  26. resource: str, should_exist: bool, context: str, namespace: str | None
  27. ) -> None:
  28. cmd = ["kubectl", "get", "--output", "name", resource, "--context", context]
  29. if namespace is not None:
  30. cmd.extend(["--namespace", namespace])
  31. ui.progress(f'running {" ".join(cmd)} ... ')
  32. try:
  33. result = subprocess.run(cmd, capture_output=True, encoding="ascii")
  34. result.check_returncode()
  35. if should_exist:
  36. ui.progress("success!", finish=True)
  37. else:
  38. raise UIError(f"{resource} exists, but expected it not to")
  39. except subprocess.CalledProcessError as e:
  40. # A bit gross, but it should be safe enough in practice.
  41. if "(NotFound)" in e.stderr:
  42. if should_exist:
  43. ui.progress("error!", finish=True)
  44. raise UIError(f"{resource} does not exist, but expected it to")
  45. else:
  46. ui.progress("success!", finish=True)
  47. else:
  48. ui.progress(finish=True)
  49. raise UIError(f"kubectl failed: {e}")