service.py 36 KB

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