service.py 22 KB

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