service.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from collections import namedtuple
  4. import logging
  5. import re
  6. import os
  7. from operator import attrgetter
  8. import sys
  9. import six
  10. from docker.errors import APIError
  11. from docker.utils import create_host_config
  12. from .config import DOCKER_CONFIG_KEYS
  13. from .container import Container, get_container_name
  14. from .progress_stream import stream_output, StreamOutputError
  15. log = logging.getLogger(__name__)
  16. DOCKER_START_KEYS = [
  17. 'cap_add',
  18. 'cap_drop',
  19. 'dns',
  20. 'dns_search',
  21. 'env_file',
  22. 'net',
  23. 'privileged',
  24. 'restart',
  25. ]
  26. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  27. class BuildError(Exception):
  28. def __init__(self, service, reason):
  29. self.service = service
  30. self.reason = reason
  31. class CannotBeScaledError(Exception):
  32. pass
  33. class ConfigError(ValueError):
  34. pass
  35. VolumeSpec = namedtuple('VolumeSpec', 'external internal mode')
  36. ServiceName = namedtuple('ServiceName', 'project service number')
  37. class Service(object):
  38. def __init__(self, name, client=None, project='default', links=None, external_links=None, volumes_from=None, net=None, **options):
  39. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  40. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  41. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  42. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  43. if 'image' in options and 'build' in options:
  44. 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)
  45. self.name = name
  46. self.client = client
  47. self.project = project
  48. self.links = links or []
  49. self.external_links = external_links or []
  50. self.volumes_from = volumes_from or []
  51. self.net = net or None
  52. self.options = options
  53. def containers(self, stopped=False, one_off=False):
  54. return [Container.from_ps(self.client, container)
  55. for container in self.client.containers(all=stopped)
  56. if self.has_container(container, one_off=one_off)]
  57. def has_container(self, container, one_off=False):
  58. """Return True if `container` was created to fulfill this service."""
  59. name = get_container_name(container)
  60. if not name or not is_valid_name(name, one_off):
  61. return False
  62. project, name, _number = parse_name(name)
  63. return project == self.project and name == self.name
  64. def get_container(self, number=1):
  65. """Return a :class:`compose.container.Container` for this service. The
  66. container must be active, and match `number`.
  67. """
  68. for container in self.client.containers():
  69. if not self.has_container(container):
  70. continue
  71. _, _, container_number = parse_name(get_container_name(container))
  72. if container_number == number:
  73. return Container.from_ps(self.client, container)
  74. raise ValueError("No container found for %s_%s" % (self.name, number))
  75. def start(self, **options):
  76. for c in self.containers(stopped=True):
  77. self.start_container_if_stopped(c, **options)
  78. def stop(self, **options):
  79. for c in self.containers():
  80. log.info("Stopping %s..." % c.name)
  81. c.stop(**options)
  82. def kill(self, **options):
  83. for c in self.containers():
  84. log.info("Killing %s..." % c.name)
  85. c.kill(**options)
  86. def restart(self, **options):
  87. for c in self.containers():
  88. log.info("Restarting %s..." % c.name)
  89. c.restart(**options)
  90. def scale(self, desired_num):
  91. """
  92. Adjusts the number of containers to the specified number and ensures
  93. they are running.
  94. - creates containers until there are at least `desired_num`
  95. - stops containers until there are at most `desired_num` running
  96. - starts containers until there are at least `desired_num` running
  97. - removes all stopped containers
  98. """
  99. if not self.can_be_scaled():
  100. raise CannotBeScaledError()
  101. # Create enough containers
  102. containers = self.containers(stopped=True)
  103. while len(containers) < desired_num:
  104. log.info("Creating %s..." % self._next_container_name(containers))
  105. containers.append(self.create_container(detach=True))
  106. running_containers = []
  107. stopped_containers = []
  108. for c in containers:
  109. if c.is_running:
  110. running_containers.append(c)
  111. else:
  112. stopped_containers.append(c)
  113. running_containers.sort(key=lambda c: c.number)
  114. stopped_containers.sort(key=lambda c: c.number)
  115. # Stop containers
  116. while len(running_containers) > desired_num:
  117. c = running_containers.pop()
  118. log.info("Stopping %s..." % c.name)
  119. c.stop(timeout=1)
  120. stopped_containers.append(c)
  121. # Start containers
  122. while len(running_containers) < desired_num:
  123. c = stopped_containers.pop(0)
  124. log.info("Starting %s..." % c.name)
  125. self.start_container(c)
  126. running_containers.append(c)
  127. self.remove_stopped()
  128. def remove_stopped(self, **options):
  129. for c in self.containers(stopped=True):
  130. if not c.is_running:
  131. log.info("Removing %s..." % c.name)
  132. c.remove(**options)
  133. def create_container(self,
  134. one_off=False,
  135. insecure_registry=False,
  136. do_build=True,
  137. intermediate_container=None,
  138. **override_options):
  139. """
  140. Create a container for this service. If the image doesn't exist, attempt to pull
  141. it.
  142. """
  143. container_options = self._get_container_create_options(
  144. override_options,
  145. one_off=one_off,
  146. intermediate_container=intermediate_container,
  147. )
  148. if (do_build and
  149. self.can_be_built() and
  150. not self.client.images(name=self.full_name)):
  151. self.build()
  152. try:
  153. return Container.create(self.client, **container_options)
  154. except APIError as e:
  155. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  156. log.info('Pulling image %s...' % container_options['image'])
  157. output = self.client.pull(
  158. container_options['image'],
  159. stream=True,
  160. insecure_registry=insecure_registry
  161. )
  162. stream_output(output, sys.stdout)
  163. return Container.create(self.client, **container_options)
  164. raise
  165. def recreate_containers(self, insecure_registry=False, do_build=True, **override_options):
  166. """
  167. If a container for this service doesn't exist, create and start one. If there are
  168. any, stop them, create+start new ones, and remove the old containers.
  169. """
  170. containers = self.containers(stopped=True)
  171. if not containers:
  172. log.info("Creating %s..." % self._next_container_name(containers))
  173. container = self.create_container(
  174. insecure_registry=insecure_registry,
  175. do_build=do_build,
  176. **override_options)
  177. self.start_container(container)
  178. return [(None, container)]
  179. else:
  180. tuples = []
  181. for c in containers:
  182. log.info("Recreating %s..." % c.name)
  183. tuples.append(self.recreate_container(c, insecure_registry=insecure_registry, **override_options))
  184. return tuples
  185. def recreate_container(self, container, **override_options):
  186. """Recreate a container. An intermediate container is created so that
  187. the new container has the same name, while still supporting
  188. `volumes-from` the original container.
  189. """
  190. try:
  191. container.stop()
  192. except APIError as e:
  193. if (e.response.status_code == 500
  194. and e.explanation
  195. and 'no such process' in str(e.explanation)):
  196. pass
  197. else:
  198. raise
  199. intermediate_container = Container.create(
  200. self.client,
  201. image=container.image,
  202. entrypoint=['/bin/echo'],
  203. command=[],
  204. detach=True,
  205. host_config=create_host_config(volumes_from=[container.id]),
  206. )
  207. intermediate_container.start()
  208. intermediate_container.wait()
  209. container.remove()
  210. options = dict(override_options)
  211. new_container = self.create_container(
  212. do_build=False,
  213. intermediate_container=intermediate_container,
  214. **options
  215. )
  216. self.start_container(new_container)
  217. intermediate_container.remove()
  218. return (intermediate_container, new_container)
  219. def start_container_if_stopped(self, container):
  220. if container.is_running:
  221. return container
  222. else:
  223. log.info("Starting %s..." % container.name)
  224. return self.start_container(container)
  225. def start_container(self, container):
  226. container.start()
  227. return container
  228. def start_or_create_containers(
  229. self,
  230. insecure_registry=False,
  231. detach=False,
  232. do_build=True):
  233. containers = self.containers(stopped=True)
  234. if not containers:
  235. log.info("Creating %s..." % self._next_container_name(containers))
  236. new_container = self.create_container(
  237. insecure_registry=insecure_registry,
  238. detach=detach,
  239. do_build=do_build,
  240. )
  241. return [self.start_container(new_container)]
  242. else:
  243. return [self.start_container_if_stopped(c) for c in containers]
  244. def get_linked_names(self):
  245. return [s.name for (s, _) in self.links]
  246. def get_volumes_from_names(self):
  247. return [s.name for s in self.volumes_from if isinstance(s, Service)]
  248. def get_net_name(self):
  249. if isinstance(self.net, Service):
  250. return self.net.name
  251. else:
  252. return
  253. def _next_container_name(self, all_containers, one_off=False):
  254. bits = [self.project, self.name]
  255. if one_off:
  256. bits.append('run')
  257. return '_'.join(bits + [str(self._next_container_number(all_containers))])
  258. def _next_container_number(self, all_containers):
  259. numbers = [parse_name(c.name).number for c in all_containers]
  260. return 1 if not numbers else max(numbers) + 1
  261. def _get_links(self, link_to_self):
  262. links = []
  263. for service, link_name in self.links:
  264. for container in service.containers():
  265. links.append((container.name, link_name or service.name))
  266. links.append((container.name, container.name))
  267. links.append((container.name, container.name_without_project))
  268. if link_to_self:
  269. for container in self.containers():
  270. links.append((container.name, self.name))
  271. links.append((container.name, container.name))
  272. links.append((container.name, container.name_without_project))
  273. for external_link in self.external_links:
  274. if ':' not in external_link:
  275. link_name = external_link
  276. else:
  277. external_link, link_name = external_link.split(':')
  278. links.append((external_link, link_name))
  279. return links
  280. def _get_volumes_from(self, intermediate_container=None):
  281. volumes_from = []
  282. for volume_source in self.volumes_from:
  283. if isinstance(volume_source, Service):
  284. containers = volume_source.containers(stopped=True)
  285. if not containers:
  286. volumes_from.append(volume_source.create_container().id)
  287. else:
  288. volumes_from.extend(map(attrgetter('id'), containers))
  289. elif isinstance(volume_source, Container):
  290. volumes_from.append(volume_source.id)
  291. if intermediate_container:
  292. volumes_from.append(intermediate_container.id)
  293. return volumes_from
  294. def _get_net(self):
  295. if not self.net:
  296. return "bridge"
  297. if isinstance(self.net, Service):
  298. containers = self.net.containers()
  299. if len(containers) > 0:
  300. net = 'container:' + containers[0].id
  301. else:
  302. log.warning("Warning: Service %s is trying to use reuse the network stack "
  303. "of another service that is not running." % (self.net.name))
  304. net = None
  305. elif isinstance(self.net, Container):
  306. net = 'container:' + self.net.id
  307. else:
  308. net = self.net
  309. return net
  310. def _get_container_create_options(self, override_options, one_off=False, intermediate_container=None):
  311. container_options = dict(
  312. (k, self.options[k])
  313. for k in DOCKER_CONFIG_KEYS if k in self.options)
  314. container_options.update(override_options)
  315. container_options['name'] = self._next_container_name(
  316. self.containers(stopped=True, one_off=one_off),
  317. one_off)
  318. # If a qualified hostname was given, split it into an
  319. # unqualified hostname and a domainname unless domainname
  320. # was also given explicitly. This matches the behavior of
  321. # the official Docker CLI in that scenario.
  322. if ('hostname' in container_options
  323. and 'domainname' not in container_options
  324. and '.' in container_options['hostname']):
  325. parts = container_options['hostname'].partition('.')
  326. container_options['hostname'] = parts[0]
  327. container_options['domainname'] = parts[2]
  328. if 'ports' in container_options or 'expose' in self.options:
  329. ports = []
  330. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  331. for port in all_ports:
  332. port = str(port)
  333. if ':' in port:
  334. port = port.split(':')[-1]
  335. if '/' in port:
  336. port = tuple(port.split('/'))
  337. ports.append(port)
  338. container_options['ports'] = ports
  339. if 'volumes' in container_options:
  340. container_options['volumes'] = dict(
  341. (parse_volume_spec(v).internal, {})
  342. for v in container_options['volumes'])
  343. if self.can_be_built():
  344. container_options['image'] = self.full_name
  345. else:
  346. container_options['image'] = self._get_image_name(container_options['image'])
  347. # Delete options which are only used when starting
  348. for key in DOCKER_START_KEYS:
  349. container_options.pop(key, None)
  350. container_options['host_config'] = self._get_container_host_config(override_options, one_off=one_off, intermediate_container=intermediate_container)
  351. return container_options
  352. def _get_container_host_config(self, override_options, one_off=False, intermediate_container=None):
  353. options = dict(self.options, **override_options)
  354. port_bindings = build_port_bindings(options.get('ports') or [])
  355. volume_bindings = dict(
  356. build_volume_binding(parse_volume_spec(volume))
  357. for volume in options.get('volumes') or []
  358. if ':' in volume)
  359. privileged = options.get('privileged', False)
  360. cap_add = options.get('cap_add', None)
  361. cap_drop = options.get('cap_drop', None)
  362. dns = options.get('dns', None)
  363. if isinstance(dns, six.string_types):
  364. dns = [dns]
  365. dns_search = options.get('dns_search', None)
  366. if isinstance(dns_search, six.string_types):
  367. dns_search = [dns_search]
  368. restart = parse_restart_spec(options.get('restart', None))
  369. return create_host_config(
  370. links=self._get_links(link_to_self=one_off),
  371. port_bindings=port_bindings,
  372. binds=volume_bindings,
  373. volumes_from=self._get_volumes_from(intermediate_container),
  374. privileged=privileged,
  375. network_mode=self._get_net(),
  376. dns=dns,
  377. dns_search=dns_search,
  378. restart_policy=restart,
  379. cap_add=cap_add,
  380. cap_drop=cap_drop,
  381. )
  382. def _get_image_name(self, image):
  383. repo, tag = parse_repository_tag(image)
  384. if tag == "":
  385. tag = "latest"
  386. return '%s:%s' % (repo, tag)
  387. def build(self, no_cache=False):
  388. log.info('Building %s...' % self.name)
  389. build_output = self.client.build(
  390. self.options['build'],
  391. tag=self.full_name,
  392. stream=True,
  393. rm=True,
  394. nocache=no_cache,
  395. )
  396. try:
  397. all_events = stream_output(build_output, sys.stdout)
  398. except StreamOutputError as e:
  399. raise BuildError(self, unicode(e))
  400. image_id = None
  401. for event in all_events:
  402. if 'stream' in event:
  403. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  404. if match:
  405. image_id = match.group(1)
  406. if image_id is None:
  407. raise BuildError(self, event if all_events else 'Unknown')
  408. return image_id
  409. def can_be_built(self):
  410. return 'build' in self.options
  411. @property
  412. def full_name(self):
  413. """
  414. The tag to give to images built for this service.
  415. """
  416. return '%s_%s' % (self.project, self.name)
  417. def can_be_scaled(self):
  418. for port in self.options.get('ports', []):
  419. if ':' in str(port):
  420. return False
  421. return True
  422. def pull(self, insecure_registry=False):
  423. if 'image' in self.options:
  424. image_name = self._get_image_name(self.options['image'])
  425. log.info('Pulling %s (%s)...' % (self.name, image_name))
  426. self.client.pull(
  427. image_name,
  428. insecure_registry=insecure_registry
  429. )
  430. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  431. def is_valid_name(name, one_off=False):
  432. match = NAME_RE.match(name)
  433. if match is None:
  434. return False
  435. if one_off:
  436. return match.group(3) == 'run_'
  437. else:
  438. return match.group(3) is None
  439. def parse_name(name):
  440. match = NAME_RE.match(name)
  441. (project, service_name, _, suffix) = match.groups()
  442. return ServiceName(project, service_name, int(suffix))
  443. def parse_restart_spec(restart_config):
  444. if not restart_config:
  445. return None
  446. parts = restart_config.split(':')
  447. if len(parts) > 2:
  448. raise ConfigError("Restart %s has incorrect format, should be "
  449. "mode[:max_retry]" % restart_config)
  450. if len(parts) == 2:
  451. name, max_retry_count = parts
  452. else:
  453. name, = parts
  454. max_retry_count = 0
  455. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  456. def parse_volume_spec(volume_config):
  457. parts = volume_config.split(':')
  458. if len(parts) > 3:
  459. raise ConfigError("Volume %s has incorrect format, should be "
  460. "external:internal[:mode]" % volume_config)
  461. if len(parts) == 1:
  462. return VolumeSpec(None, parts[0], 'rw')
  463. if len(parts) == 2:
  464. parts.append('rw')
  465. external, internal, mode = parts
  466. if mode not in ('rw', 'ro'):
  467. raise ConfigError("Volume %s has invalid mode (%s), should be "
  468. "one of: rw, ro." % (volume_config, mode))
  469. return VolumeSpec(external, internal, mode)
  470. def parse_repository_tag(s):
  471. if ":" not in s:
  472. return s, ""
  473. repo, tag = s.rsplit(":", 1)
  474. if "/" in tag:
  475. return s, ""
  476. return repo, tag
  477. def build_volume_binding(volume_spec):
  478. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  479. external = os.path.expanduser(volume_spec.external)
  480. return os.path.abspath(os.path.expandvars(external)), internal
  481. def build_port_bindings(ports):
  482. port_bindings = {}
  483. for port in ports:
  484. internal_port, external = split_port(port)
  485. if internal_port in port_bindings:
  486. port_bindings[internal_port].append(external)
  487. else:
  488. port_bindings[internal_port] = [external]
  489. return port_bindings
  490. def split_port(port):
  491. parts = str(port).split(':')
  492. if not 1 <= len(parts) <= 3:
  493. raise ConfigError('Invalid port "%s", should be '
  494. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  495. if len(parts) == 1:
  496. internal_port, = parts
  497. return internal_port, None
  498. if len(parts) == 2:
  499. external_port, internal_port = parts
  500. return internal_port, external_port
  501. external_ip, external_port, internal_port = parts
  502. return internal_port, (external_ip, external_port or None)