service.py 36 KB

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