service.py 36 KB

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