service.py 6.8 KB

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