helpers.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import contextlib
  4. import os
  5. from compose.config.config import ConfigDetails
  6. from compose.config.config import ConfigFile
  7. from compose.config.config import load
  8. BUSYBOX_IMAGE_NAME = 'busybox'
  9. BUSYBOX_DEFAULT_TAG = '1.31.0-uclibc'
  10. BUSYBOX_IMAGE_WITH_TAG = '{}:{}'.format(BUSYBOX_IMAGE_NAME, BUSYBOX_DEFAULT_TAG)
  11. def build_config(contents, **kwargs):
  12. return load(build_config_details(contents, **kwargs))
  13. def build_config_details(contents, working_dir='working_dir', filename='filename.yml'):
  14. return ConfigDetails(
  15. working_dir,
  16. [ConfigFile(filename, contents)],
  17. )
  18. def create_custom_host_file(client, filename, content):
  19. dirname = os.path.dirname(filename)
  20. container = client.create_container(
  21. BUSYBOX_IMAGE_WITH_TAG,
  22. ['sh', '-c', 'echo -n "{}" > {}'.format(content, filename)],
  23. volumes={dirname: {}},
  24. host_config=client.create_host_config(
  25. binds={dirname: {'bind': dirname, 'ro': False}},
  26. network_mode='none',
  27. ),
  28. )
  29. try:
  30. client.start(container)
  31. exitcode = client.wait(container)['StatusCode']
  32. if exitcode != 0:
  33. output = client.logs(container)
  34. raise Exception(
  35. "Container exited with code {}:\n{}".format(exitcode, output))
  36. container_info = client.inspect_container(container)
  37. if 'Node' in container_info:
  38. return container_info['Node']['Name']
  39. finally:
  40. client.remove_container(container, force=True)
  41. def create_host_file(client, filename):
  42. with open(filename, 'r') as fh:
  43. content = fh.read()
  44. return create_custom_host_file(client, filename, content)
  45. @contextlib.contextmanager
  46. def cd(path):
  47. """
  48. A context manager which changes the working directory to the given
  49. path, and then changes it back to its previous value on exit.
  50. """
  51. prev_cwd = os.getcwd()
  52. os.chdir(path)
  53. try:
  54. yield
  55. finally:
  56. os.chdir(prev_cwd)