docker.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import os
  2. import platform
  3. import stat
  4. import subprocess
  5. import sys
  6. from .log import log
  7. from .system import system
  8. def docker_run(image, extra_cmds):
  9. '''Execute commands within a docker container
  10. '''
  11. ARCH = platform.machine()
  12. if image.endswith(ARCH):
  13. bash_arg = '/pwd/run.sh'
  14. elif image.endswith('i686') and ARCH == 'x86_64':
  15. bash_arg = '-c "linux32 /pwd/run.sh"'
  16. elif image.endswith('x86_64') and ARCH == 'i686':
  17. bash_arg = '-c "linux64 /pwd/run.sh"'
  18. else:
  19. raise ValueError('Unsupported Docker image: ' + image)
  20. log('PULL', image)
  21. system(('docker', 'pull', image))
  22. script = [
  23. 'set -e',
  24. 'trap "chown -R {:}:{:} *" EXIT'.format(os.getuid(),
  25. os.getgid()),
  26. 'cd /pwd'
  27. ]
  28. script += extra_cmds
  29. with open('run.sh', 'w') as f:
  30. f.write(os.linesep.join(script))
  31. os.chmod('run.sh', stat.S_IRWXU)
  32. cmd = ' '.join(('docker', 'run', '--mount',
  33. 'type=bind,source={:},target=/pwd'.format(os.getcwd()),
  34. image, '/bin/bash', bash_arg))
  35. log('RUN', image)
  36. p = subprocess.Popen(cmd, shell=True)
  37. p.communicate()
  38. if p.returncode != 0:
  39. if p.returncode == 139:
  40. sys.stderr.write("segmentation fault when running Docker (139)\n")
  41. sys.exit(p.returncode)