service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from .packages.docker.errors import APIError
  4. import logging
  5. import re
  6. import os
  7. import sys
  8. from .container import Container
  9. from .progress_stream import stream_output, StreamOutputError
  10. log = logging.getLogger(__name__)
  11. DOCKER_CONFIG_KEYS = ['image', 'command', 'hostname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'entrypoint', 'privileged', 'volumes_from', 'net', 'working_dir']
  12. DOCKER_CONFIG_HINTS = {
  13. 'link' : 'links',
  14. 'port' : 'ports',
  15. 'privilege' : 'privileged',
  16. 'priviliged': 'privileged',
  17. 'privilige' : 'privileged',
  18. 'volume' : 'volumes',
  19. 'workdir' : 'working_dir',
  20. }
  21. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  22. class BuildError(Exception):
  23. def __init__(self, service, reason):
  24. self.service = service
  25. self.reason = reason
  26. class CannotBeScaledError(Exception):
  27. pass
  28. class ConfigError(ValueError):
  29. pass
  30. class Service(object):
  31. def __init__(self, name, client=None, project='default', links=[], volumes_from=[], **options):
  32. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  33. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  34. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  35. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  36. if 'image' in options and 'build' in options:
  37. raise ConfigError('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)
  38. supported_options = DOCKER_CONFIG_KEYS + ['build', 'expose']
  39. for k in options:
  40. if k not in supported_options:
  41. msg = "Unsupported config option for %s service: '%s'" % (name, k)
  42. if k in DOCKER_CONFIG_HINTS:
  43. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  44. raise ConfigError(msg)
  45. self.name = name
  46. self.client = client
  47. self.project = project
  48. self.links = links or []
  49. self.volumes_from = volumes_from or []
  50. self.options = options
  51. def containers(self, stopped=False, one_off=False):
  52. l = []
  53. for container in self.client.containers(all=stopped):
  54. name = get_container_name(container)
  55. if not name or not is_valid_name(name, one_off):
  56. continue
  57. project, name, number = parse_name(name)
  58. if project == self.project and name == self.name:
  59. l.append(Container.from_ps(self.client, container))
  60. return l
  61. def start(self, **options):
  62. for c in self.containers(stopped=True):
  63. self.start_container_if_stopped(c, **options)
  64. def stop(self, **options):
  65. for c in self.containers():
  66. log.info("Stopping %s..." % c.name)
  67. c.stop(**options)
  68. def kill(self, **options):
  69. for c in self.containers():
  70. log.info("Killing %s..." % c.name)
  71. c.kill(**options)
  72. def scale(self, desired_num):
  73. """
  74. Adjusts the number of containers to the specified number and ensures they are running.
  75. - creates containers until there are at least `desired_num`
  76. - stops containers until there are at most `desired_num` running
  77. - starts containers until there are at least `desired_num` running
  78. - removes all stopped containers
  79. """
  80. if not self.can_be_scaled():
  81. raise CannotBeScaledError()
  82. # Create enough containers
  83. containers = self.containers(stopped=True)
  84. while len(containers) < desired_num:
  85. containers.append(self.create_container())
  86. running_containers = []
  87. stopped_containers = []
  88. for c in containers:
  89. if c.is_running:
  90. running_containers.append(c)
  91. else:
  92. stopped_containers.append(c)
  93. running_containers.sort(key=lambda c: c.number)
  94. stopped_containers.sort(key=lambda c: c.number)
  95. # Stop containers
  96. while len(running_containers) > desired_num:
  97. c = running_containers.pop()
  98. log.info("Stopping %s..." % c.name)
  99. c.stop(timeout=1)
  100. stopped_containers.append(c)
  101. # Start containers
  102. while len(running_containers) < desired_num:
  103. c = stopped_containers.pop(0)
  104. log.info("Starting %s..." % c.name)
  105. self.start_container(c)
  106. running_containers.append(c)
  107. self.remove_stopped()
  108. def remove_stopped(self, **options):
  109. for c in self.containers(stopped=True):
  110. if not c.is_running:
  111. log.info("Removing %s..." % c.name)
  112. c.remove(**options)
  113. def create_container(self, one_off=False, **override_options):
  114. """
  115. Create a container for this service. If the image doesn't exist, attempt to pull
  116. it.
  117. """
  118. container_options = self._get_container_create_options(override_options, one_off=one_off)
  119. try:
  120. return Container.create(self.client, **container_options)
  121. except APIError as e:
  122. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  123. log.info('Pulling image %s...' % container_options['image'])
  124. output = self.client.pull(container_options['image'], stream=True)
  125. stream_output(output, sys.stdout)
  126. return Container.create(self.client, **container_options)
  127. raise
  128. def recreate_containers(self, **override_options):
  129. """
  130. If a container for this service doesn't exist, create and start one. If there are
  131. any, stop them, create+start new ones, and remove the old containers.
  132. """
  133. containers = self.containers(stopped=True)
  134. if len(containers) == 0:
  135. log.info("Creating %s..." % self.next_container_name())
  136. container = self.create_container(**override_options)
  137. self.start_container(container)
  138. return [(None, container)]
  139. else:
  140. tuples = []
  141. for c in containers:
  142. log.info("Recreating %s..." % c.name)
  143. tuples.append(self.recreate_container(c, **override_options))
  144. return tuples
  145. def recreate_container(self, container, **override_options):
  146. if container.is_running:
  147. container.stop(timeout=1)
  148. intermediate_container = Container.create(
  149. self.client,
  150. image=container.image,
  151. entrypoint=['echo'],
  152. command=[],
  153. )
  154. intermediate_container.start(volumes_from=container.id)
  155. intermediate_container.wait()
  156. container.remove()
  157. options = dict(override_options)
  158. new_container = self.create_container(**options)
  159. self.start_container(new_container, intermediate_container=intermediate_container)
  160. intermediate_container.remove()
  161. return (intermediate_container, new_container)
  162. def start_container_if_stopped(self, container, **options):
  163. if container.is_running:
  164. return container
  165. else:
  166. log.info("Starting %s..." % container.name)
  167. return self.start_container(container, **options)
  168. def start_container(self, container=None, intermediate_container=None,**override_options):
  169. if container is None:
  170. container = self.create_container(**override_options)
  171. options = self.options.copy()
  172. options.update(override_options)
  173. port_bindings = {}
  174. if options.get('ports', None) is not None:
  175. for port in options['ports']:
  176. internal_port, external_port = split_port(port)
  177. port_bindings[internal_port] = external_port
  178. volume_bindings = {}
  179. if options.get('volumes', None) is not None:
  180. for volume in options['volumes']:
  181. if ':' in volume:
  182. external_dir, internal_dir = volume.split(':')
  183. volume_bindings[os.path.abspath(external_dir)] = {
  184. 'bind': internal_dir,
  185. 'ro': False,
  186. }
  187. privileged = options.get('privileged', False)
  188. net = options.get('net', 'bridge')
  189. container.start(
  190. links=self._get_links(link_to_self=override_options.get('one_off', False)),
  191. port_bindings=port_bindings,
  192. binds=volume_bindings,
  193. volumes_from=self._get_volumes_from(intermediate_container),
  194. privileged=privileged,
  195. network_mode=net,
  196. )
  197. return container
  198. def start_or_create_containers(self):
  199. containers = self.containers(stopped=True)
  200. if len(containers) == 0:
  201. log.info("Creating %s..." % self.next_container_name())
  202. new_container = self.create_container()
  203. return [self.start_container(new_container)]
  204. else:
  205. return [self.start_container_if_stopped(c) for c in containers]
  206. def get_linked_names(self):
  207. return [s.name for (s, _) in self.links]
  208. def next_container_name(self, one_off=False):
  209. bits = [self.project, self.name]
  210. if one_off:
  211. bits.append('run')
  212. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  213. def next_container_number(self, one_off=False):
  214. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  215. if len(numbers) == 0:
  216. return 1
  217. else:
  218. return max(numbers) + 1
  219. def _get_links(self, link_to_self):
  220. links = []
  221. for service, link_name in self.links:
  222. for container in service.containers():
  223. if link_name:
  224. links.append((container.name, link_name))
  225. links.append((container.name, container.name))
  226. links.append((container.name, container.name_without_project))
  227. if link_to_self:
  228. for container in self.containers():
  229. links.append((container.name, container.name))
  230. links.append((container.name, container.name_without_project))
  231. return links
  232. def _get_volumes_from(self, intermediate_container=None):
  233. volumes_from = []
  234. for v in self.volumes_from:
  235. if isinstance(v, Service):
  236. for container in v.containers(stopped=True):
  237. volumes_from.append(container.id)
  238. elif isinstance(v, Container):
  239. volumes_from.append(v.id)
  240. if intermediate_container:
  241. volumes_from.append(intermediate_container.id)
  242. return volumes_from
  243. def _get_container_create_options(self, override_options, one_off=False):
  244. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  245. container_options.update(override_options)
  246. container_options['name'] = self.next_container_name(one_off)
  247. if 'ports' in container_options or 'expose' in self.options:
  248. ports = []
  249. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  250. for port in all_ports:
  251. port = str(port)
  252. if ':' in port:
  253. port = port.split(':')[-1]
  254. if '/' in port:
  255. port = tuple(port.split('/'))
  256. ports.append(port)
  257. container_options['ports'] = ports
  258. if 'volumes' in container_options:
  259. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  260. if self.can_be_built():
  261. if len(self.client.images(name=self._build_tag_name())) == 0:
  262. self.build()
  263. container_options['image'] = self._build_tag_name()
  264. # Priviliged is only required for starting containers, not for creating them
  265. if 'privileged' in container_options:
  266. del container_options['privileged']
  267. # net is only required for starting containers, not for creating them
  268. if 'net' in container_options:
  269. del container_options['net']
  270. return container_options
  271. def build(self):
  272. log.info('Building %s...' % self.name)
  273. build_output = self.client.build(
  274. self.options['build'],
  275. tag=self._build_tag_name(),
  276. stream=True,
  277. rm=True
  278. )
  279. try:
  280. all_events = stream_output(build_output, sys.stdout)
  281. except StreamOutputError, e:
  282. raise BuildError(self, unicode(e))
  283. image_id = None
  284. for event in all_events:
  285. if 'stream' in event:
  286. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  287. if match:
  288. image_id = match.group(1)
  289. if image_id is None:
  290. raise BuildError(self)
  291. return image_id
  292. def can_be_built(self):
  293. return 'build' in self.options
  294. def _build_tag_name(self):
  295. """
  296. The tag to give to images built for this service.
  297. """
  298. return '%s_%s' % (self.project, self.name)
  299. def can_be_scaled(self):
  300. for port in self.options.get('ports', []):
  301. if ':' in str(port):
  302. return False
  303. return True
  304. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  305. def is_valid_name(name, one_off=False):
  306. match = NAME_RE.match(name)
  307. if match is None:
  308. return False
  309. if one_off:
  310. return match.group(3) == 'run_'
  311. else:
  312. return match.group(3) is None
  313. def parse_name(name, one_off=False):
  314. match = NAME_RE.match(name)
  315. (project, service_name, _, suffix) = match.groups()
  316. return (project, service_name, int(suffix))
  317. def get_container_name(container):
  318. if not container.get('Name') and not container.get('Names'):
  319. return None
  320. # inspect
  321. if 'Name' in container:
  322. return container['Name']
  323. # ps
  324. for name in container['Names']:
  325. if len(name.split('/')) == 2:
  326. return name[1:]
  327. def split_volume(v):
  328. """
  329. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  330. If v is of the format INTERNAL, returns (None, INTERNAL).
  331. """
  332. if ':' in v:
  333. return v.split(':', 1)
  334. else:
  335. return (None, v)
  336. def split_port(port):
  337. port = str(port)
  338. external_ip = None
  339. if ':' in port:
  340. external_port, internal_port = port.rsplit(':', 1)
  341. if ':' in external_port:
  342. external_ip, external_port = external_port.split(':', 1)
  343. else:
  344. external_port, internal_port = (None, port)
  345. if external_ip:
  346. if external_port:
  347. external_port = (external_ip, external_port)
  348. else:
  349. external_port = (external_ip,)
  350. return internal_port, external_port