service.py 8.7 KB

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