service.py 22 KB

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