helpers.py 1.9 KB

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