docker_api.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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_containers():
  16. client = get_docker_client()
  17. containers = []
  18. if not client:
  19. return containers
  20. for container in client.containers.list():
  21. containers.append({
  22. 'id': container.id,
  23. 'short_id': container.short_id,
  24. 'name': container.name,
  25. 'image': container.image,
  26. 'labels': container.labels,
  27. 'status': container.status
  28. })
  29. return containers
  30. '''
  31. '''
  32. def get_all_images():
  33. client = get_docker_client()
  34. images = []
  35. if not client:
  36. return images
  37. for image in client.images.list():
  38. images.append({
  39. 'id': image.id,
  40. 'short_id': image.short_id,
  41. 'tags': image.tags
  42. })
  43. '''
  44. '''
  45. def start_container(id=None):
  46. if not id:
  47. return False
  48. client = get_docker_client()
  49. if not client:
  50. return False
  51. try:
  52. container = client.containers.get(id)
  53. container.start()
  54. except NotFound:
  55. return False
  56. except APIError:
  57. return
  58. '''
  59. '''
  60. def stop_container(id=None):
  61. if not id:
  62. return False
  63. client = get_docker_client()
  64. if not client:
  65. return False
  66. try:
  67. container = client.containers.get(id)
  68. container.stop()
  69. except NotFound:
  70. return False
  71. except APIError:
  72. return