docker_api.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.conf import settings
  4. from docker import DockerClient
  5. from docker.errors import DockerException, NotFound, APIError
  6. '''
  7. '''
  8. def get_docker_client():
  9. try:
  10. return DockerClient(base_url='unix:/%s' % settings.DOCKER_SOCK_DIR)
  11. except DockerException:
  12. return None
  13. '''
  14. '''
  15. def get_all_images():
  16. client = get_docker_client()
  17. images = []
  18. if not client:
  19. return images
  20. for image in client.images.list():
  21. images.append({
  22. 'id': image.id,
  23. 'short_id': image.short_id,
  24. 'tags': image.tags
  25. })
  26. return images
  27. '''
  28. '''
  29. def get_all_containers():
  30. client = get_docker_client()
  31. containers = []
  32. if not client:
  33. return containers
  34. for container in client.containers.list():
  35. containers.append({
  36. 'id': container.id,
  37. 'short_id': container.short_id,
  38. 'name': container.name,
  39. 'image': container.image,
  40. 'labels': container.labels,
  41. 'status': container.status
  42. })
  43. return containers
  44. '''
  45. '''
  46. def start_container(id=None):
  47. if not id:
  48. return False
  49. client = get_docker_client()
  50. if not client:
  51. return False
  52. try:
  53. container = client.containers.get(id)
  54. container.start()
  55. except NotFound:
  56. return False
  57. except APIError:
  58. return
  59. '''
  60. '''
  61. def stop_container(id=None):
  62. if not id:
  63. return False
  64. client = get_docker_client()
  65. if not client:
  66. return False
  67. try:
  68. container = client.containers.get(id)
  69. container.stop()
  70. except NotFound:
  71. return False
  72. except APIError:
  73. return False