service.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import re
  5. import sys
  6. from collections import namedtuple
  7. from operator import attrgetter
  8. import enum
  9. import six
  10. from docker.errors import APIError
  11. from docker.utils import LogConfig
  12. from docker.utils.ports import build_port_bindings
  13. from docker.utils.ports import split_port
  14. from . import __version__
  15. from . import progress_stream
  16. from .config import DOCKER_CONFIG_KEYS
  17. from .config import merge_environment
  18. from .config.types import VolumeSpec
  19. from .const import DEFAULT_TIMEOUT
  20. from .const import LABEL_CONFIG_HASH
  21. from .const import LABEL_CONTAINER_NUMBER
  22. from .const import LABEL_ONE_OFF
  23. from .const import LABEL_PROJECT
  24. from .const import LABEL_SERVICE
  25. from .const import LABEL_VERSION
  26. from .container import Container
  27. from .parallel import parallel_execute
  28. from .parallel import parallel_start
  29. from .progress_stream import stream_output
  30. from .progress_stream import StreamOutputError
  31. from .utils import json_hash
  32. log = logging.getLogger(__name__)
  33. DOCKER_START_KEYS = [
  34. 'cap_add',
  35. 'cap_drop',
  36. 'cgroup_parent',
  37. 'cpu_quota',
  38. 'devices',
  39. 'dns',
  40. 'dns_search',
  41. 'env_file',
  42. 'extra_hosts',
  43. 'ipc',
  44. 'read_only',
  45. 'log_driver',
  46. 'log_opt',
  47. 'mem_limit',
  48. 'memswap_limit',
  49. 'pid',
  50. 'privileged',
  51. 'restart',
  52. 'security_opt',
  53. 'shm_size',
  54. 'volumes_from',
  55. ]
  56. class BuildError(Exception):
  57. def __init__(self, service, reason):
  58. self.service = service
  59. self.reason = reason
  60. class NeedsBuildError(Exception):
  61. def __init__(self, service):
  62. self.service = service
  63. class NoSuchImageError(Exception):
  64. pass
  65. ServiceName = namedtuple('ServiceName', 'project service number')
  66. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  67. @enum.unique
  68. class ConvergenceStrategy(enum.Enum):
  69. """Enumeration for all possible convergence strategies. Values refer to
  70. when containers should be recreated.
  71. """
  72. changed = 1
  73. always = 2
  74. never = 3
  75. @property
  76. def allows_recreate(self):
  77. return self is not type(self).never
  78. @enum.unique
  79. class ImageType(enum.Enum):
  80. """Enumeration for the types of images known to compose."""
  81. none = 0
  82. local = 1
  83. all = 2
  84. @enum.unique
  85. class BuildAction(enum.Enum):
  86. """Enumeration for the possible build actions."""
  87. none = 0
  88. force = 1
  89. skip = 2
  90. class Service(object):
  91. def __init__(
  92. self,
  93. name,
  94. client=None,
  95. project='default',
  96. use_networking=False,
  97. links=None,
  98. volumes_from=None,
  99. network_mode=None,
  100. networks=None,
  101. **options
  102. ):
  103. self.name = name
  104. self.client = client
  105. self.project = project
  106. self.use_networking = use_networking
  107. self.links = links or []
  108. self.volumes_from = volumes_from or []
  109. self.network_mode = network_mode or NetworkMode(None)
  110. self.networks = networks or {}
  111. self.options = options
  112. def __repr__(self):
  113. return '<Service: {}>'.format(self.name)
  114. def containers(self, stopped=False, one_off=False, filters={}):
  115. filters.update({'label': self.labels(one_off=one_off)})
  116. return list(filter(None, [
  117. Container.from_ps(self.client, container)
  118. for container in self.client.containers(
  119. all=stopped,
  120. filters=filters)]))
  121. def get_container(self, number=1):
  122. """Return a :class:`compose.container.Container` for this service. The
  123. container must be active, and match `number`.
  124. """
  125. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  126. for container in self.client.containers(filters={'label': labels}):
  127. return Container.from_ps(self.client, container)
  128. raise ValueError("No container found for %s_%s" % (self.name, number))
  129. def start(self, **options):
  130. containers = self.containers(stopped=True)
  131. for c in containers:
  132. self.start_container_if_stopped(c, **options)
  133. return containers
  134. def scale(self, desired_num, timeout=DEFAULT_TIMEOUT):
  135. """
  136. Adjusts the number of containers to the specified number and ensures
  137. they are running.
  138. - creates containers until there are at least `desired_num`
  139. - stops containers until there are at most `desired_num` running
  140. - starts containers until there are at least `desired_num` running
  141. - removes all stopped containers
  142. """
  143. if self.custom_container_name and desired_num > 1:
  144. log.warn('The "%s" service is using the custom container name "%s". '
  145. 'Docker requires each container to have a unique name. '
  146. 'Remove the custom name to scale the service.'
  147. % (self.name, self.custom_container_name))
  148. if self.specifies_host_port() and desired_num > 1:
  149. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  150. 'for this service are created on a single host, the port will clash.'
  151. % self.name)
  152. def create_and_start(service, number):
  153. container = service.create_container(number=number, quiet=True)
  154. service.start_container(container)
  155. return container
  156. def stop_and_remove(container):
  157. container.stop(timeout=timeout)
  158. container.remove()
  159. running_containers = self.containers(stopped=False)
  160. num_running = len(running_containers)
  161. if desired_num == num_running:
  162. # do nothing as we already have the desired number
  163. log.info('Desired container number already achieved')
  164. return
  165. if desired_num > num_running:
  166. # we need to start/create until we have desired_num
  167. all_containers = self.containers(stopped=True)
  168. if num_running != len(all_containers):
  169. # we have some stopped containers, let's start them up again
  170. stopped_containers = sorted(
  171. (c for c in all_containers if not c.is_running),
  172. key=attrgetter('number'))
  173. num_stopped = len(stopped_containers)
  174. if num_stopped + num_running > desired_num:
  175. num_to_start = desired_num - num_running
  176. containers_to_start = stopped_containers[:num_to_start]
  177. else:
  178. containers_to_start = stopped_containers
  179. parallel_start(containers_to_start, {})
  180. num_running += len(containers_to_start)
  181. num_to_create = desired_num - num_running
  182. next_number = self._next_container_number()
  183. container_numbers = [
  184. number for number in range(
  185. next_number, next_number + num_to_create
  186. )
  187. ]
  188. parallel_execute(
  189. container_numbers,
  190. lambda n: create_and_start(service=self, number=n),
  191. lambda n: self.get_container_name(n),
  192. "Creating and starting"
  193. )
  194. if desired_num < num_running:
  195. num_to_stop = num_running - desired_num
  196. sorted_running_containers = sorted(
  197. running_containers,
  198. key=attrgetter('number'))
  199. parallel_execute(
  200. sorted_running_containers[-num_to_stop:],
  201. stop_and_remove,
  202. lambda c: c.name,
  203. "Stopping and removing",
  204. )
  205. def create_container(self,
  206. one_off=False,
  207. previous_container=None,
  208. number=None,
  209. quiet=False,
  210. **override_options):
  211. """
  212. Create a container for this service. If the image doesn't exist, attempt to pull
  213. it.
  214. """
  215. # This is only necessary for `scale` and `volumes_from`
  216. # auto-creating containers to satisfy the dependency.
  217. self.ensure_image_exists()
  218. container_options = self._get_container_create_options(
  219. override_options,
  220. number or self._next_container_number(one_off=one_off),
  221. one_off=one_off,
  222. previous_container=previous_container,
  223. )
  224. if 'name' in container_options and not quiet:
  225. log.info("Creating %s" % container_options['name'])
  226. return Container.create(self.client, **container_options)
  227. def ensure_image_exists(self, do_build=BuildAction.none):
  228. if self.can_be_built() and do_build == BuildAction.force:
  229. self.build()
  230. return
  231. try:
  232. self.image()
  233. return
  234. except NoSuchImageError:
  235. pass
  236. if not self.can_be_built():
  237. self.pull()
  238. return
  239. if do_build == BuildAction.skip:
  240. raise NeedsBuildError(self)
  241. self.build()
  242. log.warn(
  243. "Image for service {} was built because it did not already exist. To "
  244. "rebuild this image you must use `docker-compose build` or "
  245. "`docker-compose up --build`.".format(self.name))
  246. def image(self):
  247. try:
  248. return self.client.inspect_image(self.image_name)
  249. except APIError as e:
  250. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  251. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  252. else:
  253. raise
  254. @property
  255. def image_name(self):
  256. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  257. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  258. containers = self.containers(stopped=True)
  259. if not containers:
  260. return ConvergencePlan('create', [])
  261. if strategy is ConvergenceStrategy.never:
  262. return ConvergencePlan('start', containers)
  263. if (
  264. strategy is ConvergenceStrategy.always or
  265. self._containers_have_diverged(containers)
  266. ):
  267. return ConvergencePlan('recreate', containers)
  268. stopped = [c for c in containers if not c.is_running]
  269. if stopped:
  270. return ConvergencePlan('start', stopped)
  271. return ConvergencePlan('noop', containers)
  272. def _containers_have_diverged(self, containers):
  273. config_hash = None
  274. try:
  275. config_hash = self.config_hash
  276. except NoSuchImageError as e:
  277. log.debug(
  278. 'Service %s has diverged: %s',
  279. self.name, six.text_type(e),
  280. )
  281. return True
  282. has_diverged = False
  283. for c in containers:
  284. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  285. if container_config_hash != config_hash:
  286. log.debug(
  287. '%s has diverged: %s != %s',
  288. c.name, container_config_hash, config_hash,
  289. )
  290. has_diverged = True
  291. return has_diverged
  292. def execute_convergence_plan(self,
  293. plan,
  294. timeout=DEFAULT_TIMEOUT,
  295. detached=False,
  296. start=True):
  297. (action, containers) = plan
  298. should_attach_logs = not detached
  299. if action == 'create':
  300. container = self.create_container()
  301. if should_attach_logs:
  302. container.attach_log_stream()
  303. if start:
  304. self.start_container(container)
  305. return [container]
  306. elif action == 'recreate':
  307. return [
  308. self.recreate_container(
  309. container,
  310. timeout=timeout,
  311. attach_logs=should_attach_logs,
  312. start_new_container=start
  313. )
  314. for container in containers
  315. ]
  316. elif action == 'start':
  317. if start:
  318. for container in containers:
  319. self.start_container_if_stopped(container, attach_logs=should_attach_logs)
  320. return containers
  321. elif action == 'noop':
  322. for c in containers:
  323. log.info("%s is up-to-date" % c.name)
  324. return containers
  325. else:
  326. raise Exception("Invalid action: {}".format(action))
  327. def recreate_container(
  328. self,
  329. container,
  330. timeout=DEFAULT_TIMEOUT,
  331. attach_logs=False,
  332. start_new_container=True):
  333. """Recreate a container.
  334. The original container is renamed to a temporary name so that data
  335. volumes can be copied to the new container, before the original
  336. container is removed.
  337. """
  338. log.info("Recreating %s" % container.name)
  339. container.stop(timeout=timeout)
  340. container.rename_to_tmp_name()
  341. new_container = self.create_container(
  342. previous_container=container,
  343. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  344. quiet=True,
  345. )
  346. if attach_logs:
  347. new_container.attach_log_stream()
  348. if start_new_container:
  349. self.start_container(new_container)
  350. container.remove()
  351. return new_container
  352. def start_container_if_stopped(self, container, attach_logs=False, quiet=False):
  353. if not container.is_running:
  354. if not quiet:
  355. log.info("Starting %s" % container.name)
  356. if attach_logs:
  357. container.attach_log_stream()
  358. return self.start_container(container)
  359. def start_container(self, container):
  360. self.connect_container_to_networks(container)
  361. container.start()
  362. return container
  363. def connect_container_to_networks(self, container):
  364. connected_networks = container.get('NetworkSettings.Networks')
  365. for network, netdefs in self.networks.items():
  366. if network in connected_networks:
  367. if short_id_alias_exists(container, network):
  368. continue
  369. self.client.disconnect_container_from_network(
  370. container.id,
  371. network)
  372. self.client.connect_container_to_network(
  373. container.id, network,
  374. aliases=self._get_aliases(netdefs, container),
  375. ipv4_address=netdefs.get('ipv4_address', None),
  376. ipv6_address=netdefs.get('ipv6_address', None),
  377. links=self._get_links(False))
  378. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  379. for c in self.duplicate_containers():
  380. log.info('Removing %s' % c.name)
  381. c.stop(timeout=timeout)
  382. c.remove()
  383. def duplicate_containers(self):
  384. containers = sorted(
  385. self.containers(stopped=True),
  386. key=lambda c: c.get('Created'),
  387. )
  388. numbers = set()
  389. for c in containers:
  390. if c.number in numbers:
  391. yield c
  392. else:
  393. numbers.add(c.number)
  394. @property
  395. def config_hash(self):
  396. return json_hash(self.config_dict())
  397. def config_dict(self):
  398. return {
  399. 'options': self.options,
  400. 'image_id': self.image()['Id'],
  401. 'links': self.get_link_names(),
  402. 'net': self.network_mode.id,
  403. 'networks': self.networks,
  404. 'volumes_from': [
  405. (v.source.name, v.mode)
  406. for v in self.volumes_from if isinstance(v.source, Service)
  407. ],
  408. }
  409. def get_dependency_names(self):
  410. net_name = self.network_mode.service_name
  411. return (self.get_linked_service_names() +
  412. self.get_volumes_from_names() +
  413. ([net_name] if net_name else []) +
  414. self.options.get('depends_on', []))
  415. def get_linked_service_names(self):
  416. return [service.name for (service, _) in self.links]
  417. def get_link_names(self):
  418. return [(service.name, alias) for service, alias in self.links]
  419. def get_volumes_from_names(self):
  420. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  421. # TODO: this would benefit from github.com/docker/docker/pull/14699
  422. # to remove the need to inspect every container
  423. def _next_container_number(self, one_off=False):
  424. containers = filter(None, [
  425. Container.from_ps(self.client, container)
  426. for container in self.client.containers(
  427. all=True,
  428. filters={'label': self.labels(one_off=one_off)})
  429. ])
  430. numbers = [c.number for c in containers]
  431. return 1 if not numbers else max(numbers) + 1
  432. def _get_aliases(self, network, container=None):
  433. if container and container.labels.get(LABEL_ONE_OFF) == "True":
  434. return []
  435. return list(
  436. {self.name} |
  437. ({container.short_id} if container else set()) |
  438. set(network.get('aliases', ()))
  439. )
  440. def build_default_networking_config(self):
  441. if not self.networks:
  442. return {}
  443. network = self.networks[self.network_mode.id]
  444. endpoint = {
  445. 'Aliases': self._get_aliases(network),
  446. 'IPAMConfig': {},
  447. }
  448. if network.get('ipv4_address'):
  449. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  450. if network.get('ipv6_address'):
  451. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  452. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  453. def _get_links(self, link_to_self):
  454. links = {}
  455. for service, link_name in self.links:
  456. for container in service.containers():
  457. links[link_name or service.name] = container.name
  458. links[container.name] = container.name
  459. links[container.name_without_project] = container.name
  460. if link_to_self:
  461. for container in self.containers():
  462. links[self.name] = container.name
  463. links[container.name] = container.name
  464. links[container.name_without_project] = container.name
  465. for external_link in self.options.get('external_links') or []:
  466. if ':' not in external_link:
  467. link_name = external_link
  468. else:
  469. external_link, link_name = external_link.split(':')
  470. links[link_name] = external_link
  471. return [
  472. (alias, container_name)
  473. for (container_name, alias) in links.items()
  474. ]
  475. def _get_volumes_from(self):
  476. return [build_volume_from(spec) for spec in self.volumes_from]
  477. def _get_container_create_options(
  478. self,
  479. override_options,
  480. number,
  481. one_off=False,
  482. previous_container=None):
  483. add_config_hash = (not one_off and not override_options)
  484. container_options = dict(
  485. (k, self.options[k])
  486. for k in DOCKER_CONFIG_KEYS if k in self.options)
  487. container_options.update(override_options)
  488. if not container_options.get('name'):
  489. container_options['name'] = self.get_container_name(number, one_off)
  490. container_options.setdefault('detach', True)
  491. # If a qualified hostname was given, split it into an
  492. # unqualified hostname and a domainname unless domainname
  493. # was also given explicitly. This matches the behavior of
  494. # the official Docker CLI in that scenario.
  495. if ('hostname' in container_options and
  496. 'domainname' not in container_options and
  497. '.' in container_options['hostname']):
  498. parts = container_options['hostname'].partition('.')
  499. container_options['hostname'] = parts[0]
  500. container_options['domainname'] = parts[2]
  501. if 'ports' in container_options or 'expose' in self.options:
  502. container_options['ports'] = build_container_ports(
  503. container_options,
  504. self.options)
  505. container_options['environment'] = merge_environment(
  506. self.options.get('environment'),
  507. override_options.get('environment'))
  508. binds, affinity = merge_volume_bindings(
  509. container_options.get('volumes') or [],
  510. previous_container)
  511. override_options['binds'] = binds
  512. container_options['environment'].update(affinity)
  513. if 'volumes' in container_options:
  514. container_options['volumes'] = dict(
  515. (v.internal, {}) for v in container_options['volumes'])
  516. container_options['image'] = self.image_name
  517. container_options['labels'] = build_container_labels(
  518. container_options.get('labels', {}),
  519. self.labels(one_off=one_off),
  520. number,
  521. self.config_hash if add_config_hash else None)
  522. # Delete options which are only used when starting
  523. for key in DOCKER_START_KEYS:
  524. container_options.pop(key, None)
  525. container_options['host_config'] = self._get_container_host_config(
  526. override_options,
  527. one_off=one_off)
  528. networking_config = self.build_default_networking_config()
  529. if networking_config:
  530. container_options['networking_config'] = networking_config
  531. container_options['environment'] = format_environment(
  532. container_options['environment'])
  533. return container_options
  534. def _get_container_host_config(self, override_options, one_off=False):
  535. options = dict(self.options, **override_options)
  536. logging_dict = options.get('logging', None)
  537. log_config = get_log_config(logging_dict)
  538. return self.client.create_host_config(
  539. links=self._get_links(link_to_self=one_off),
  540. port_bindings=build_port_bindings(options.get('ports') or []),
  541. binds=options.get('binds'),
  542. volumes_from=self._get_volumes_from(),
  543. privileged=options.get('privileged', False),
  544. network_mode=self.network_mode.mode,
  545. devices=options.get('devices'),
  546. dns=options.get('dns'),
  547. dns_search=options.get('dns_search'),
  548. restart_policy=options.get('restart'),
  549. cap_add=options.get('cap_add'),
  550. cap_drop=options.get('cap_drop'),
  551. mem_limit=options.get('mem_limit'),
  552. memswap_limit=options.get('memswap_limit'),
  553. ulimits=build_ulimits(options.get('ulimits')),
  554. log_config=log_config,
  555. extra_hosts=options.get('extra_hosts'),
  556. read_only=options.get('read_only'),
  557. pid_mode=options.get('pid'),
  558. security_opt=options.get('security_opt'),
  559. ipc_mode=options.get('ipc'),
  560. cgroup_parent=options.get('cgroup_parent'),
  561. cpu_quota=options.get('cpu_quota'),
  562. shm_size=options.get('shm_size'),
  563. tmpfs=options.get('tmpfs'),
  564. )
  565. def build(self, no_cache=False, pull=False, force_rm=False):
  566. log.info('Building %s' % self.name)
  567. build_opts = self.options.get('build', {})
  568. path = build_opts.get('context')
  569. # python2 os.path() doesn't support unicode, so we need to encode it to
  570. # a byte string
  571. if not six.PY3:
  572. path = path.encode('utf8')
  573. build_output = self.client.build(
  574. path=path,
  575. tag=self.image_name,
  576. stream=True,
  577. rm=True,
  578. forcerm=force_rm,
  579. pull=pull,
  580. nocache=no_cache,
  581. dockerfile=build_opts.get('dockerfile', None),
  582. buildargs=build_opts.get('args', None),
  583. )
  584. try:
  585. all_events = stream_output(build_output, sys.stdout)
  586. except StreamOutputError as e:
  587. raise BuildError(self, six.text_type(e))
  588. # Ensure the HTTP connection is not reused for another
  589. # streaming command, as the Docker daemon can sometimes
  590. # complain about it
  591. self.client.close()
  592. image_id = None
  593. for event in all_events:
  594. if 'stream' in event:
  595. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  596. if match:
  597. image_id = match.group(1)
  598. if image_id is None:
  599. raise BuildError(self, event if all_events else 'Unknown')
  600. return image_id
  601. def can_be_built(self):
  602. return 'build' in self.options
  603. def labels(self, one_off=False):
  604. return [
  605. '{0}={1}'.format(LABEL_PROJECT, self.project),
  606. '{0}={1}'.format(LABEL_SERVICE, self.name),
  607. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  608. ]
  609. @property
  610. def custom_container_name(self):
  611. return self.options.get('container_name')
  612. def get_container_name(self, number, one_off=False):
  613. if self.custom_container_name and not one_off:
  614. return self.custom_container_name
  615. return build_container_name(self.project, self.name, number, one_off)
  616. def remove_image(self, image_type):
  617. if not image_type or image_type == ImageType.none:
  618. return False
  619. if image_type == ImageType.local and self.options.get('image'):
  620. return False
  621. log.info("Removing image %s", self.image_name)
  622. try:
  623. self.client.remove_image(self.image_name)
  624. return True
  625. except APIError as e:
  626. log.error("Failed to remove image for service %s: %s", self.name, e)
  627. return False
  628. def specifies_host_port(self):
  629. def has_host_port(binding):
  630. _, external_bindings = split_port(binding)
  631. # there are no external bindings
  632. if external_bindings is None:
  633. return False
  634. # we only need to check the first binding from the range
  635. external_binding = external_bindings[0]
  636. # non-tuple binding means there is a host port specified
  637. if not isinstance(external_binding, tuple):
  638. return True
  639. # extract actual host port from tuple of (host_ip, host_port)
  640. _, host_port = external_binding
  641. if host_port is not None:
  642. return True
  643. return False
  644. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  645. def pull(self, ignore_pull_failures=False):
  646. if 'image' not in self.options:
  647. return
  648. repo, tag, separator = parse_repository_tag(self.options['image'])
  649. tag = tag or 'latest'
  650. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  651. output = self.client.pull(repo, tag=tag, stream=True)
  652. try:
  653. return progress_stream.get_digest_from_pull(
  654. stream_output(output, sys.stdout))
  655. except StreamOutputError as e:
  656. if not ignore_pull_failures:
  657. raise
  658. else:
  659. log.error(six.text_type(e))
  660. def push(self, ignore_push_failures=False):
  661. if 'image' not in self.options or 'build' not in self.options:
  662. return
  663. repo, tag, separator = parse_repository_tag(self.options['image'])
  664. tag = tag or 'latest'
  665. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  666. output = self.client.push(repo, tag=tag, stream=True)
  667. try:
  668. return progress_stream.get_digest_from_push(
  669. stream_output(output, sys.stdout))
  670. except StreamOutputError as e:
  671. if not ignore_push_failures:
  672. raise
  673. else:
  674. log.error(six.text_type(e))
  675. def short_id_alias_exists(container, network):
  676. aliases = container.get(
  677. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  678. return container.short_id in aliases
  679. class NetworkMode(object):
  680. """A `standard` network mode (ex: host, bridge)"""
  681. service_name = None
  682. def __init__(self, network_mode):
  683. self.network_mode = network_mode
  684. @property
  685. def id(self):
  686. return self.network_mode
  687. mode = id
  688. class ContainerNetworkMode(object):
  689. """A network mode that uses a container's network stack."""
  690. service_name = None
  691. def __init__(self, container):
  692. self.container = container
  693. @property
  694. def id(self):
  695. return self.container.id
  696. @property
  697. def mode(self):
  698. return 'container:' + self.container.id
  699. class ServiceNetworkMode(object):
  700. """A network mode that uses a service's network stack."""
  701. def __init__(self, service):
  702. self.service = service
  703. @property
  704. def id(self):
  705. return self.service.name
  706. service_name = id
  707. @property
  708. def mode(self):
  709. containers = self.service.containers()
  710. if containers:
  711. return 'container:' + containers[0].id
  712. log.warn("Service %s is trying to use reuse the network stack "
  713. "of another service that is not running." % (self.id))
  714. return None
  715. # Names
  716. def build_container_name(project, service, number, one_off=False):
  717. bits = [project, service]
  718. if one_off:
  719. bits.append('run')
  720. return '_'.join(bits + [str(number)])
  721. # Images
  722. def parse_repository_tag(repo_path):
  723. """Splits image identification into base image path, tag/digest
  724. and it's separator.
  725. Example:
  726. >>> parse_repository_tag('user/repo@sha256:digest')
  727. ('user/repo', 'sha256:digest', '@')
  728. >>> parse_repository_tag('user/repo:v1')
  729. ('user/repo', 'v1', ':')
  730. """
  731. tag_separator = ":"
  732. digest_separator = "@"
  733. if digest_separator in repo_path:
  734. repo, tag = repo_path.rsplit(digest_separator, 1)
  735. return repo, tag, digest_separator
  736. repo, tag = repo_path, ""
  737. if tag_separator in repo_path:
  738. repo, tag = repo_path.rsplit(tag_separator, 1)
  739. if "/" in tag:
  740. repo, tag = repo_path, ""
  741. return repo, tag, tag_separator
  742. # Volumes
  743. def merge_volume_bindings(volumes, previous_container):
  744. """Return a list of volume bindings for a container. Container data volumes
  745. are replaced by those from the previous container.
  746. """
  747. affinity = {}
  748. volume_bindings = dict(
  749. build_volume_binding(volume)
  750. for volume in volumes
  751. if volume.external)
  752. if previous_container:
  753. old_volumes = get_container_data_volumes(previous_container, volumes)
  754. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  755. volume_bindings.update(
  756. build_volume_binding(volume) for volume in old_volumes)
  757. if old_volumes:
  758. affinity = {'affinity:container': '=' + previous_container.id}
  759. return list(volume_bindings.values()), affinity
  760. def get_container_data_volumes(container, volumes_option):
  761. """Find the container data volumes that are in `volumes_option`, and return
  762. a mapping of volume bindings for those volumes.
  763. """
  764. volumes = []
  765. volumes_option = volumes_option or []
  766. container_mounts = dict(
  767. (mount['Destination'], mount)
  768. for mount in container.get('Mounts') or {}
  769. )
  770. image_volumes = [
  771. VolumeSpec.parse(volume)
  772. for volume in
  773. container.image_config['ContainerConfig'].get('Volumes') or {}
  774. ]
  775. for volume in set(volumes_option + image_volumes):
  776. # No need to preserve host volumes
  777. if volume.external:
  778. continue
  779. mount = container_mounts.get(volume.internal)
  780. # New volume, doesn't exist in the old container
  781. if not mount:
  782. continue
  783. # Volume was previously a host volume, now it's a container volume
  784. if not mount.get('Name'):
  785. continue
  786. # Copy existing volume from old container
  787. volume = volume._replace(external=mount['Name'])
  788. volumes.append(volume)
  789. return volumes
  790. def warn_on_masked_volume(volumes_option, container_volumes, service):
  791. container_volumes = dict(
  792. (volume.internal, volume.external)
  793. for volume in container_volumes)
  794. for volume in volumes_option:
  795. if (
  796. volume.external and
  797. volume.internal in container_volumes and
  798. container_volumes.get(volume.internal) != volume.external
  799. ):
  800. log.warn((
  801. "Service \"{service}\" is using volume \"{volume}\" from the "
  802. "previous container. Host mapping \"{host_path}\" has no effect. "
  803. "Remove the existing containers (with `docker-compose rm {service}`) "
  804. "to use the host volume mapping."
  805. ).format(
  806. service=service,
  807. volume=volume.internal,
  808. host_path=volume.external))
  809. def build_volume_binding(volume_spec):
  810. return volume_spec.internal, volume_spec.repr()
  811. def build_volume_from(volume_from_spec):
  812. """
  813. volume_from can be either a service or a container. We want to return the
  814. container.id and format it into a string complete with the mode.
  815. """
  816. if isinstance(volume_from_spec.source, Service):
  817. containers = volume_from_spec.source.containers(stopped=True)
  818. if not containers:
  819. return "{}:{}".format(
  820. volume_from_spec.source.create_container().id,
  821. volume_from_spec.mode)
  822. container = containers[0]
  823. return "{}:{}".format(container.id, volume_from_spec.mode)
  824. elif isinstance(volume_from_spec.source, Container):
  825. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  826. # Labels
  827. def build_container_labels(label_options, service_labels, number, config_hash):
  828. labels = dict(label_options or {})
  829. labels.update(label.split('=', 1) for label in service_labels)
  830. labels[LABEL_CONTAINER_NUMBER] = str(number)
  831. labels[LABEL_VERSION] = __version__
  832. if config_hash:
  833. log.debug("Added config hash: %s" % config_hash)
  834. labels[LABEL_CONFIG_HASH] = config_hash
  835. return labels
  836. # Ulimits
  837. def build_ulimits(ulimit_config):
  838. if not ulimit_config:
  839. return None
  840. ulimits = []
  841. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  842. if isinstance(soft_hard_values, six.integer_types):
  843. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  844. elif isinstance(soft_hard_values, dict):
  845. ulimit_dict = {'name': limit_name}
  846. ulimit_dict.update(soft_hard_values)
  847. ulimits.append(ulimit_dict)
  848. return ulimits
  849. def get_log_config(logging_dict):
  850. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  851. log_options = logging_dict.get('options', None) if logging_dict else None
  852. return LogConfig(
  853. type=log_driver,
  854. config=log_options
  855. )
  856. # TODO: remove once fix is available in docker-py
  857. def format_environment(environment):
  858. def format_env(key, value):
  859. if value is None:
  860. return key
  861. return '{key}={value}'.format(key=key, value=value)
  862. return [format_env(*item) for item in environment.items()]
  863. # Ports
  864. def build_container_ports(container_options, options):
  865. ports = []
  866. all_ports = container_options.get('ports', []) + options.get('expose', [])
  867. for port_range in all_ports:
  868. internal_range, _ = split_port(port_range)
  869. for port in internal_range:
  870. port = str(port)
  871. if '/' in port:
  872. port = tuple(port.split('/'))
  873. ports.append(port)
  874. return ports