service.py 32 KB

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