service.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 them and create new ones. Does not remove the old containers.
  67. """
  68. containers = self.containers(stopped=True)
  69. if len(containers) == 0:
  70. return ([], [self.create_container(**override_options)])
  71. else:
  72. old_containers = []
  73. new_containers = []
  74. for c in containers:
  75. (old_container, new_container) = self.recreate_container(c, **override_options)
  76. old_containers.append(old_container)
  77. new_containers.append(new_container)
  78. return (old_containers, new_containers)
  79. def recreate_container(self, container, **override_options):
  80. if container.is_running:
  81. container.stop(timeout=1)
  82. options = dict(override_options)
  83. options['volumes_from'] = container.id
  84. return (container, self.create_container(**options))
  85. def start_container(self, container=None, **override_options):
  86. if container is None:
  87. container = self.create_container(**override_options)
  88. options = self.options.copy()
  89. options.update(override_options)
  90. port_bindings = {}
  91. if options.get('ports', None) is not None:
  92. for port in options['ports']:
  93. port = str(port)
  94. if ':' in port:
  95. external_port, internal_port = port.split(':', 1)
  96. port_bindings[int(internal_port)] = int(external_port)
  97. else:
  98. port_bindings[int(port)] = None
  99. volume_bindings = {}
  100. if options.get('volumes', None) is not None:
  101. for volume in options['volumes']:
  102. if ':' in volume:
  103. external_dir, internal_dir = volume.split(':')
  104. volume_bindings[os.path.abspath(external_dir)] = internal_dir
  105. container.start(
  106. links=self._get_links(),
  107. port_bindings=port_bindings,
  108. binds=volume_bindings,
  109. )
  110. return container
  111. def next_container_name(self, one_off=False):
  112. bits = [self.project, self.name]
  113. if one_off:
  114. bits.append('run')
  115. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  116. def next_container_number(self, one_off=False):
  117. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  118. if len(numbers) == 0:
  119. return 1
  120. else:
  121. return max(numbers) + 1
  122. def _get_links(self):
  123. links = {}
  124. for service in self.links:
  125. for container in service.containers():
  126. links[container.name] = container.name
  127. return links
  128. def _get_container_options(self, override_options, one_off=False):
  129. keys = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'volumes_from']
  130. container_options = dict((k, self.options[k]) for k in keys if k in self.options)
  131. container_options.update(override_options)
  132. container_options['name'] = self.next_container_name(one_off)
  133. if 'ports' in container_options:
  134. ports = []
  135. for port in container_options['ports']:
  136. port = str(port)
  137. if ':' in port:
  138. port = port.split(':')[-1]
  139. ports.append(port)
  140. container_options['ports'] = ports
  141. if 'volumes' in container_options:
  142. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  143. if self.can_be_built():
  144. if len(self.client.images(name=self._build_tag_name())) == 0:
  145. self.build()
  146. container_options['image'] = self._build_tag_name()
  147. return container_options
  148. def build(self):
  149. log.info('Building %s...' % self.name)
  150. build_output = self.client.build(
  151. self.options['build'],
  152. tag=self._build_tag_name(),
  153. stream=True
  154. )
  155. image_id = None
  156. for line in build_output:
  157. if line:
  158. match = re.search(r'Successfully built ([0-9a-f]+)', line)
  159. if match:
  160. image_id = match.group(1)
  161. sys.stdout.write(line)
  162. if image_id is None:
  163. raise BuildError()
  164. return image_id
  165. def can_be_built(self):
  166. return 'build' in self.options
  167. def _build_tag_name(self):
  168. """
  169. The tag to give to images built for this service.
  170. """
  171. return '%s_%s' % (self.project, self.name)
  172. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  173. def is_valid_name(name, one_off=False):
  174. match = NAME_RE.match(name)
  175. if match is None:
  176. return False
  177. if one_off:
  178. return match.group(3) == 'run_'
  179. else:
  180. return match.group(3) is None
  181. def parse_name(name, one_off=False):
  182. match = NAME_RE.match(name)
  183. (project, service_name, _, suffix) = match.groups()
  184. return (project, service_name, int(suffix))
  185. def get_container_name(container):
  186. if not container.get('Name') and not container.get('Names'):
  187. return None
  188. # inspect
  189. if 'Name' in container:
  190. return container['Name']
  191. # ps
  192. for name in container['Names']:
  193. if len(name.split('/')) == 2:
  194. return name[1:]
  195. def split_volume(v):
  196. """
  197. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  198. If v is of the format INTERNAL, returns (None, INTERNAL).
  199. """
  200. if ':' in v:
  201. return v.split(':', 1)
  202. else:
  203. return (None, v)