service.py 36 KB

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