service.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. log.info("Starting %s..." % c.name)
  39. self.start_container(c, **options)
  40. def stop(self, **options):
  41. for c in self.containers():
  42. log.info("Stopping %s..." % c.name)
  43. c.stop(**options)
  44. def kill(self, **options):
  45. for c in self.containers():
  46. log.info("Killing %s..." % c.name)
  47. c.kill(**options)
  48. def remove_stopped(self, **options):
  49. for c in self.containers(stopped=True):
  50. if not c.is_running:
  51. log.info("Removing %s..." % c.name)
  52. c.remove(**options)
  53. def create_container(self, one_off=False, **override_options):
  54. """
  55. Create a container for this service. If the image doesn't exist, attempt to pull
  56. it.
  57. """
  58. container_options = self._get_container_options(override_options, one_off=one_off)
  59. try:
  60. return Container.create(self.client, **container_options)
  61. except APIError as e:
  62. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  63. log.info('Pulling image %s...' % container_options['image'])
  64. self.client.pull(container_options['image'])
  65. return Container.create(self.client, **container_options)
  66. raise
  67. def recreate_containers(self, **override_options):
  68. """
  69. If a container for this service doesn't exist, create one. If there are
  70. any, stop them and create new ones. Does not remove the old containers.
  71. """
  72. containers = self.containers(stopped=True)
  73. if len(containers) == 0:
  74. log.info("Creating %s..." % self.next_container_name())
  75. return ([], [self.create_container(**override_options)])
  76. else:
  77. old_containers = []
  78. new_containers = []
  79. for c in containers:
  80. log.info("Recreating %s..." % c.name)
  81. (old_container, new_container) = self.recreate_container(c, **override_options)
  82. old_containers.append(old_container)
  83. new_containers.append(new_container)
  84. return (old_containers, new_containers)
  85. def recreate_container(self, container, **override_options):
  86. if container.is_running:
  87. container.stop(timeout=1)
  88. intermediate_container = Container.create(
  89. self.client,
  90. image='ubuntu',
  91. command='echo',
  92. volumes_from=container.id,
  93. )
  94. intermediate_container.start()
  95. intermediate_container.wait()
  96. container.remove()
  97. options = dict(override_options)
  98. options['volumes_from'] = intermediate_container.id
  99. new_container = self.create_container(**options)
  100. return (intermediate_container, new_container)
  101. def start_container(self, container=None, **override_options):
  102. if container is None:
  103. container = self.create_container(**override_options)
  104. options = self.options.copy()
  105. options.update(override_options)
  106. port_bindings = {}
  107. if options.get('ports', None) is not None:
  108. for port in options['ports']:
  109. port = str(port)
  110. if ':' in port:
  111. external_port, internal_port = port.split(':', 1)
  112. port_bindings[int(internal_port)] = int(external_port)
  113. else:
  114. port_bindings[int(port)] = None
  115. volume_bindings = {}
  116. if options.get('volumes', None) is not None:
  117. for volume in options['volumes']:
  118. if ':' in volume:
  119. external_dir, internal_dir = volume.split(':')
  120. volume_bindings[os.path.abspath(external_dir)] = internal_dir
  121. container.start(
  122. links=self._get_links(),
  123. port_bindings=port_bindings,
  124. binds=volume_bindings,
  125. )
  126. return container
  127. def next_container_name(self, one_off=False):
  128. bits = [self.project, self.name]
  129. if one_off:
  130. bits.append('run')
  131. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  132. def next_container_number(self, one_off=False):
  133. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  134. if len(numbers) == 0:
  135. return 1
  136. else:
  137. return max(numbers) + 1
  138. def _get_links(self):
  139. links = {}
  140. for service in self.links:
  141. for container in service.containers():
  142. links[container.name] = container.name
  143. return links
  144. def _get_container_options(self, override_options, one_off=False):
  145. keys = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'volumes_from']
  146. container_options = dict((k, self.options[k]) for k in keys if k in self.options)
  147. container_options.update(override_options)
  148. container_options['name'] = self.next_container_name(one_off)
  149. if 'ports' in container_options:
  150. ports = []
  151. for port in container_options['ports']:
  152. port = str(port)
  153. if ':' in port:
  154. port = port.split(':')[-1]
  155. ports.append(port)
  156. container_options['ports'] = ports
  157. if 'volumes' in container_options:
  158. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  159. if self.can_be_built():
  160. if len(self.client.images(name=self._build_tag_name())) == 0:
  161. self.build()
  162. container_options['image'] = self._build_tag_name()
  163. return container_options
  164. def build(self):
  165. log.info('Building %s...' % self.name)
  166. build_output = self.client.build(
  167. self.options['build'],
  168. tag=self._build_tag_name(),
  169. stream=True
  170. )
  171. image_id = None
  172. for line in build_output:
  173. if line:
  174. match = re.search(r'Successfully built ([0-9a-f]+)', line)
  175. if match:
  176. image_id = match.group(1)
  177. sys.stdout.write(line)
  178. if image_id is None:
  179. raise BuildError()
  180. return image_id
  181. def can_be_built(self):
  182. return 'build' in self.options
  183. def _build_tag_name(self):
  184. """
  185. The tag to give to images built for this service.
  186. """
  187. return '%s_%s' % (self.project, self.name)
  188. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  189. def is_valid_name(name, one_off=False):
  190. match = NAME_RE.match(name)
  191. if match is None:
  192. return False
  193. if one_off:
  194. return match.group(3) == 'run_'
  195. else:
  196. return match.group(3) is None
  197. def parse_name(name, one_off=False):
  198. match = NAME_RE.match(name)
  199. (project, service_name, _, suffix) = match.groups()
  200. return (project, service_name, int(suffix))
  201. def get_container_name(container):
  202. if not container.get('Name') and not container.get('Names'):
  203. return None
  204. # inspect
  205. if 'Name' in container:
  206. return container['Name']
  207. # ps
  208. for name in container['Names']:
  209. if len(name.split('/')) == 2:
  210. return name[1:]
  211. def split_volume(v):
  212. """
  213. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  214. If v is of the format INTERNAL, returns (None, INTERNAL).
  215. """
  216. if ':' in v:
  217. return v.split(':', 1)
  218. else:
  219. return (None, v)