service.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from docker.client import APIError
  4. import logging
  5. import re
  6. import os
  7. import sys
  8. from .container import Container
  9. log = logging.getLogger(__name__)
  10. class BuildError(Exception):
  11. pass
  12. class Service(object):
  13. def __init__(self, name, client=None, project='default', links=[], **options):
  14. if not re.match('^[a-zA-Z0-9]+$', name):
  15. raise ValueError('Invalid name: %s' % name)
  16. if not re.match('^[a-zA-Z0-9]+$', project):
  17. raise ValueError('Invalid project: %s' % project)
  18. if 'image' in options and 'build' in options:
  19. raise ValueError('Service %s has both an image and build path specified. A service can either be built to image or use an existing image, not both.' % name)
  20. self.name = name
  21. self.client = client
  22. self.project = project
  23. self.links = links or []
  24. self.options = options
  25. def containers(self, stopped=False, one_off=False):
  26. l = []
  27. for container in self.client.containers(all=stopped):
  28. name = get_container_name(container)
  29. if not name or not is_valid_name(name, one_off):
  30. continue
  31. project, name, number = parse_name(name)
  32. if project == self.project and name == self.name:
  33. l.append(Container.from_ps(self.client, container))
  34. return l
  35. def start(self, **options):
  36. for c in self.containers(stopped=True):
  37. if not c.is_running:
  38. self.start_container(c, **options)
  39. def stop(self, **options):
  40. for c in self.containers():
  41. c.stop(**options)
  42. def kill(self, **options):
  43. for c in self.containers():
  44. c.kill(**options)
  45. def remove_stopped(self, **options):
  46. for c in self.containers(stopped=True):
  47. if not c.is_running:
  48. c.remove(**options)
  49. def create_container(self, one_off=False, **override_options):
  50. """
  51. Create a container for this service. If the image doesn't exist, attempt to pull
  52. it.
  53. """
  54. container_options = self._get_container_options(override_options, one_off=one_off)
  55. try:
  56. return Container.create(self.client, **container_options)
  57. except APIError as e:
  58. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  59. log.info('Pulling image %s...' % container_options['image'])
  60. self.client.pull(container_options['image'])
  61. return Container.create(self.client, **container_options)
  62. raise
  63. def recreate_containers(self, **override_options):
  64. """
  65. If a container for this service doesn't exist, create one. If there are
  66. any, stop, remove and recreate them.
  67. """
  68. containers = self.containers(stopped=True)
  69. if len(containers) == 0:
  70. return [self.create_container(**override_options)]
  71. else:
  72. new_containers = []
  73. for old_container in containers:
  74. if old_container.is_running:
  75. old_container.stop()
  76. options = dict(override_options)
  77. options['volumes_from'] = old_container.id
  78. new_containers.append(self.create_container(**options))
  79. old_container.remove()
  80. return new_containers
  81. def start_container(self, container=None, **override_options):
  82. if container is None:
  83. container = self.create_container(**override_options)
  84. options = self.options.copy()
  85. options.update(override_options)
  86. port_bindings = {}
  87. if options.get('ports', None) is not None:
  88. for port in options['ports']:
  89. port = str(port)
  90. if ':' in port:
  91. external_port, internal_port = port.split(':', 1)
  92. port_bindings[int(internal_port)] = int(external_port)
  93. else:
  94. port_bindings[int(port)] = None
  95. volume_bindings = {}
  96. if options.get('volumes', None) is not None:
  97. for volume in options['volumes']:
  98. if ':' in volume:
  99. external_dir, internal_dir = volume.split(':')
  100. volume_bindings[os.path.abspath(external_dir)] = internal_dir
  101. container.start(
  102. links=self._get_links(),
  103. port_bindings=port_bindings,
  104. binds=volume_bindings,
  105. )
  106. return container
  107. def next_container_name(self, one_off=False):
  108. bits = [self.project, self.name]
  109. if one_off:
  110. bits.append('run')
  111. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  112. def next_container_number(self, one_off=False):
  113. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  114. if len(numbers) == 0:
  115. return 1
  116. else:
  117. return max(numbers) + 1
  118. def _get_links(self):
  119. links = {}
  120. for service in self.links:
  121. for container in service.containers():
  122. links[container.name] = container.name
  123. return links
  124. def _get_container_options(self, override_options, one_off=False):
  125. keys = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'volumes_from']
  126. container_options = dict((k, self.options[k]) for k in keys if k in self.options)
  127. container_options.update(override_options)
  128. container_options['name'] = self.next_container_name(one_off)
  129. if 'ports' in container_options:
  130. ports = []
  131. for port in container_options['ports']:
  132. port = str(port)
  133. if ':' in port:
  134. port = port.split(':')[-1]
  135. ports.append(port)
  136. container_options['ports'] = ports
  137. if 'volumes' in container_options:
  138. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  139. if self.can_be_built():
  140. if len(self.client.images(name=self._build_tag_name())) == 0:
  141. self.build()
  142. container_options['image'] = self._build_tag_name()
  143. return container_options
  144. def build(self):
  145. log.info('Building %s...' % self.name)
  146. build_output = self.client.build(
  147. self.options['build'],
  148. tag=self._build_tag_name(),
  149. stream=True
  150. )
  151. image_id = None
  152. for line in build_output:
  153. if line:
  154. match = re.search(r'Successfully built ([0-9a-f]+)', line)
  155. if match:
  156. image_id = match.group(1)
  157. sys.stdout.write(line)
  158. if image_id is None:
  159. raise BuildError()
  160. return image_id
  161. def can_be_built(self):
  162. return 'build' in self.options
  163. def _build_tag_name(self):
  164. """
  165. The tag to give to images built for this service.
  166. """
  167. return '%s_%s' % (self.project, self.name)
  168. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  169. def is_valid_name(name, one_off=False):
  170. match = NAME_RE.match(name)
  171. if match is None:
  172. return False
  173. if one_off:
  174. return match.group(3) == 'run_'
  175. else:
  176. return match.group(3) is None
  177. def parse_name(name, one_off=False):
  178. match = NAME_RE.match(name)
  179. (project, service_name, _, suffix) = match.groups()
  180. return (project, service_name, int(suffix))
  181. def get_container_name(container):
  182. if not container.get('Name') and not container.get('Names'):
  183. return None
  184. # inspect
  185. if 'Name' in container:
  186. return container['Name']
  187. # ps
  188. for name in container['Names']:
  189. if len(name.split('/')) == 2:
  190. return name[1:]
  191. def split_volume(v):
  192. """
  193. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  194. If v is of the format INTERNAL, returns (None, INTERNAL).
  195. """
  196. if ':' in v:
  197. return v.split(':', 1)
  198. else:
  199. return (None, v)