service.py 36 KB

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