1
0

helpers.py 1.9 KB

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