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