docker_wrapper.py 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. """Wrap docker commands for easier create docker container."""
  18. import time
  19. from typing import Optional
  20. import docker
  21. from docker.errors import ImageNotFound
  22. from docker.models.containers import Container
  23. class DockerWrapper:
  24. """Wrap docker commands for easier create docker container.
  25. :param image: The image to create docker container.
  26. """
  27. def __init__(self, image: str, container_name: str):
  28. self._client = docker.from_env()
  29. self.image = image
  30. self.container_name = container_name
  31. def run(self, *args, **kwargs) -> Container:
  32. """Create and run a new container.
  33. This method would return immediately after the container started, if you wish it return container
  34. object when specific service start, you could see :func:`run_until_log` which return container
  35. object when specific output log appear in docker.
  36. """
  37. if not self.images_exists:
  38. raise ValueError("Docker image named %s do not exists.", self.image)
  39. return self._client.containers.run(
  40. image=self.image, name=self.container_name, detach=True, *args, **kwargs
  41. )
  42. def run_until_log(
  43. self, log: str, remove_exists: Optional[bool] = True, *args, **kwargs
  44. ) -> Container:
  45. """Create and run a new container, return when specific log appear.
  46. It will call :func:`run` inside this method. And after container started, it would not
  47. return it immediately but run command `docker logs` to see whether specific log appear.
  48. It will raise `RuntimeError` when 10 minutes after but specific log do not appear.
  49. """
  50. if remove_exists:
  51. self.remove_container()
  52. log_byte = str.encode(log)
  53. container = self.run(*args, **kwargs)
  54. timeout_threshold = 10 * 60
  55. start_time = time.time()
  56. while time.time() <= start_time + timeout_threshold:
  57. if log_byte in container.logs(tail=1000):
  58. break
  59. time.sleep(2)
  60. # Stop container and raise error when reach timeout threshold but do not appear specific log output
  61. else:
  62. container.remove(force=True)
  63. raise RuntimeError(
  64. "Can not capture specific log `%s` in %d seconds, remove container.",
  65. (log, timeout_threshold),
  66. )
  67. return container
  68. def remove_container(self):
  69. """Remove container which already running."""
  70. containers = self._client.containers.list(
  71. all=True, filters={"name": self.container_name}
  72. )
  73. if containers:
  74. for container in containers:
  75. container.remove(force=True)
  76. @property
  77. def images_exists(self) -> bool:
  78. """Check whether the image exists in local docker repository or not."""
  79. try:
  80. self._client.images.get(self.image)
  81. return True
  82. except ImageNotFound:
  83. return False