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. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  390. for c in self.duplicate_containers():
  391. log.info('Removing %s' % c.name)
  392. c.stop(timeout=timeout)
  393. c.remove()
  394. def duplicate_containers(self):
  395. containers = sorted(
  396. self.containers(stopped=True),
  397. key=lambda c: c.get('Created'),
  398. )
  399. numbers = set()
  400. for c in containers:
  401. if c.number in numbers:
  402. yield c
  403. else:
  404. numbers.add(c.number)
  405. @property
  406. def config_hash(self):
  407. return json_hash(self.config_dict())
  408. def config_dict(self):
  409. return {
  410. 'options': self.options,
  411. 'image_id': self.image()['Id'],
  412. 'links': self.get_link_names(),
  413. 'net': self.network_mode.id,
  414. 'networks': self.networks,
  415. 'volumes_from': [
  416. (v.source.name, v.mode)
  417. for v in self.volumes_from if isinstance(v.source, Service)
  418. ],
  419. }
  420. def get_dependency_names(self):
  421. net_name = self.network_mode.service_name
  422. return (self.get_linked_service_names() +
  423. self.get_volumes_from_names() +
  424. ([net_name] if net_name else []) +
  425. self.options.get('depends_on', []))
  426. def get_linked_service_names(self):
  427. return [service.name for (service, _) in self.links]
  428. def get_link_names(self):
  429. return [(service.name, alias) for service, alias in self.links]
  430. def get_volumes_from_names(self):
  431. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  432. # TODO: this would benefit from github.com/docker/docker/pull/14699
  433. # to remove the need to inspect every container
  434. def _next_container_number(self, one_off=False):
  435. containers = filter(None, [
  436. Container.from_ps(self.client, container)
  437. for container in self.client.containers(
  438. all=True,
  439. filters={'label': self.labels(one_off=one_off)})
  440. ])
  441. numbers = [c.number for c in containers]
  442. return 1 if not numbers else max(numbers) + 1
  443. def _get_aliases(self, network, container=None):
  444. if container and container.labels.get(LABEL_ONE_OFF) == "True":
  445. return []
  446. return list(
  447. {self.name} |
  448. ({container.short_id} if container else set()) |
  449. set(network.get('aliases', ()))
  450. )
  451. def build_default_networking_config(self):
  452. if not self.networks:
  453. return {}
  454. network = self.networks[self.network_mode.id]
  455. endpoint = {
  456. 'Aliases': self._get_aliases(network),
  457. 'IPAMConfig': {},
  458. }
  459. if network.get('ipv4_address'):
  460. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  461. if network.get('ipv6_address'):
  462. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  463. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  464. def _get_links(self, link_to_self):
  465. links = {}
  466. for service, link_name in self.links:
  467. for container in service.containers():
  468. links[link_name or service.name] = container.name
  469. links[container.name] = container.name
  470. links[container.name_without_project] = container.name
  471. if link_to_self:
  472. for container in self.containers():
  473. links[self.name] = container.name
  474. links[container.name] = container.name
  475. links[container.name_without_project] = container.name
  476. for external_link in self.options.get('external_links') or []:
  477. if ':' not in external_link:
  478. link_name = external_link
  479. else:
  480. external_link, link_name = external_link.split(':')
  481. links[link_name] = external_link
  482. return [
  483. (alias, container_name)
  484. for (container_name, alias) in links.items()
  485. ]
  486. def _get_volumes_from(self):
  487. return [build_volume_from(spec) for spec in self.volumes_from]
  488. def _get_container_create_options(
  489. self,
  490. override_options,
  491. number,
  492. one_off=False,
  493. previous_container=None):
  494. add_config_hash = (not one_off and not override_options)
  495. container_options = dict(
  496. (k, self.options[k])
  497. for k in DOCKER_CONFIG_KEYS if k in self.options)
  498. container_options.update(override_options)
  499. if not container_options.get('name'):
  500. container_options['name'] = self.get_container_name(number, one_off)
  501. container_options.setdefault('detach', True)
  502. # If a qualified hostname was given, split it into an
  503. # unqualified hostname and a domainname unless domainname
  504. # was also given explicitly. This matches the behavior of
  505. # the official Docker CLI in that scenario.
  506. if ('hostname' in container_options and
  507. 'domainname' not in container_options and
  508. '.' in container_options['hostname']):
  509. parts = container_options['hostname'].partition('.')
  510. container_options['hostname'] = parts[0]
  511. container_options['domainname'] = parts[2]
  512. if 'ports' in container_options or 'expose' in self.options:
  513. container_options['ports'] = build_container_ports(
  514. container_options,
  515. self.options)
  516. container_options['environment'] = merge_environment(
  517. self.options.get('environment'),
  518. override_options.get('environment'))
  519. binds, affinity = merge_volume_bindings(
  520. container_options.get('volumes') or [],
  521. previous_container)
  522. override_options['binds'] = binds
  523. container_options['environment'].update(affinity)
  524. if 'volumes' in container_options:
  525. container_options['volumes'] = dict(
  526. (v.internal, {}) for v in container_options['volumes'])
  527. container_options['image'] = self.image_name
  528. container_options['labels'] = build_container_labels(
  529. container_options.get('labels', {}),
  530. self.labels(one_off=one_off),
  531. number,
  532. self.config_hash if add_config_hash else None)
  533. # Delete options which are only used when starting
  534. for key in DOCKER_START_KEYS:
  535. container_options.pop(key, None)
  536. container_options['host_config'] = self._get_container_host_config(
  537. override_options,
  538. one_off=one_off)
  539. networking_config = self.build_default_networking_config()
  540. if networking_config:
  541. container_options['networking_config'] = networking_config
  542. container_options['environment'] = format_environment(
  543. container_options['environment'])
  544. return container_options
  545. def _get_container_host_config(self, override_options, one_off=False):
  546. options = dict(self.options, **override_options)
  547. logging_dict = options.get('logging', None)
  548. log_config = get_log_config(logging_dict)
  549. return self.client.create_host_config(
  550. links=self._get_links(link_to_self=one_off),
  551. port_bindings=build_port_bindings(options.get('ports') or []),
  552. binds=options.get('binds'),
  553. volumes_from=self._get_volumes_from(),
  554. privileged=options.get('privileged', False),
  555. network_mode=self.network_mode.mode,
  556. devices=options.get('devices'),
  557. dns=options.get('dns'),
  558. dns_search=options.get('dns_search'),
  559. restart_policy=options.get('restart'),
  560. cap_add=options.get('cap_add'),
  561. cap_drop=options.get('cap_drop'),
  562. mem_limit=options.get('mem_limit'),
  563. memswap_limit=options.get('memswap_limit'),
  564. ulimits=build_ulimits(options.get('ulimits')),
  565. log_config=log_config,
  566. extra_hosts=options.get('extra_hosts'),
  567. read_only=options.get('read_only'),
  568. pid_mode=options.get('pid'),
  569. security_opt=options.get('security_opt'),
  570. ipc_mode=options.get('ipc'),
  571. cgroup_parent=options.get('cgroup_parent'),
  572. cpu_quota=options.get('cpu_quota'),
  573. shm_size=options.get('shm_size'),
  574. tmpfs=options.get('tmpfs'),
  575. oom_score_adj=options.get('oom_score_adj'),
  576. mem_swappiness=options.get('mem_swappiness'),
  577. group_add=options.get('group_add')
  578. )
  579. def build(self, no_cache=False, pull=False, force_rm=False):
  580. log.info('Building %s' % self.name)
  581. build_opts = self.options.get('build', {})
  582. path = build_opts.get('context')
  583. # python2 os.path() doesn't support unicode, so we need to encode it to
  584. # a byte string
  585. if not six.PY3:
  586. path = path.encode('utf8')
  587. build_output = self.client.build(
  588. path=path,
  589. tag=self.image_name,
  590. stream=True,
  591. rm=True,
  592. forcerm=force_rm,
  593. pull=pull,
  594. nocache=no_cache,
  595. dockerfile=build_opts.get('dockerfile', None),
  596. buildargs=build_opts.get('args', None),
  597. )
  598. try:
  599. all_events = stream_output(build_output, sys.stdout)
  600. except StreamOutputError as e:
  601. raise BuildError(self, six.text_type(e))
  602. # Ensure the HTTP connection is not reused for another
  603. # streaming command, as the Docker daemon can sometimes
  604. # complain about it
  605. self.client.close()
  606. image_id = None
  607. for event in all_events:
  608. if 'stream' in event:
  609. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  610. if match:
  611. image_id = match.group(1)
  612. if image_id is None:
  613. raise BuildError(self, event if all_events else 'Unknown')
  614. return image_id
  615. def can_be_built(self):
  616. return 'build' in self.options
  617. def labels(self, one_off=False):
  618. return [
  619. '{0}={1}'.format(LABEL_PROJECT, self.project),
  620. '{0}={1}'.format(LABEL_SERVICE, self.name),
  621. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  622. ]
  623. @property
  624. def custom_container_name(self):
  625. return self.options.get('container_name')
  626. def get_container_name(self, number, one_off=False):
  627. if self.custom_container_name and not one_off:
  628. return self.custom_container_name
  629. return build_container_name(self.project, self.name, number, one_off)
  630. def remove_image(self, image_type):
  631. if not image_type or image_type == ImageType.none:
  632. return False
  633. if image_type == ImageType.local and self.options.get('image'):
  634. return False
  635. log.info("Removing image %s", self.image_name)
  636. try:
  637. self.client.remove_image(self.image_name)
  638. return True
  639. except APIError as e:
  640. log.error("Failed to remove image for service %s: %s", self.name, e)
  641. return False
  642. def specifies_host_port(self):
  643. def has_host_port(binding):
  644. _, external_bindings = split_port(binding)
  645. # there are no external bindings
  646. if external_bindings is None:
  647. return False
  648. # we only need to check the first binding from the range
  649. external_binding = external_bindings[0]
  650. # non-tuple binding means there is a host port specified
  651. if not isinstance(external_binding, tuple):
  652. return True
  653. # extract actual host port from tuple of (host_ip, host_port)
  654. _, host_port = external_binding
  655. if host_port is not None:
  656. return True
  657. return False
  658. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  659. def pull(self, ignore_pull_failures=False):
  660. if 'image' not in self.options:
  661. return
  662. repo, tag, separator = parse_repository_tag(self.options['image'])
  663. tag = tag or 'latest'
  664. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  665. output = self.client.pull(repo, tag=tag, stream=True)
  666. try:
  667. return progress_stream.get_digest_from_pull(
  668. stream_output(output, sys.stdout))
  669. except StreamOutputError as e:
  670. if not ignore_pull_failures:
  671. raise
  672. else:
  673. log.error(six.text_type(e))
  674. def push(self, ignore_push_failures=False):
  675. if 'image' not in self.options or 'build' not in self.options:
  676. return
  677. repo, tag, separator = parse_repository_tag(self.options['image'])
  678. tag = tag or 'latest'
  679. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  680. output = self.client.push(repo, tag=tag, stream=True)
  681. try:
  682. return progress_stream.get_digest_from_push(
  683. stream_output(output, sys.stdout))
  684. except StreamOutputError as e:
  685. if not ignore_push_failures:
  686. raise
  687. else:
  688. log.error(six.text_type(e))
  689. def short_id_alias_exists(container, network):
  690. aliases = container.get(
  691. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  692. return container.short_id in aliases
  693. class NetworkMode(object):
  694. """A `standard` network mode (ex: host, bridge)"""
  695. service_name = None
  696. def __init__(self, network_mode):
  697. self.network_mode = network_mode
  698. @property
  699. def id(self):
  700. return self.network_mode
  701. mode = id
  702. class ContainerNetworkMode(object):
  703. """A network mode that uses a container's network stack."""
  704. service_name = None
  705. def __init__(self, container):
  706. self.container = container
  707. @property
  708. def id(self):
  709. return self.container.id
  710. @property
  711. def mode(self):
  712. return 'container:' + self.container.id
  713. class ServiceNetworkMode(object):
  714. """A network mode that uses a service's network stack."""
  715. def __init__(self, service):
  716. self.service = service
  717. @property
  718. def id(self):
  719. return self.service.name
  720. service_name = id
  721. @property
  722. def mode(self):
  723. containers = self.service.containers()
  724. if containers:
  725. return 'container:' + containers[0].id
  726. log.warn("Service %s is trying to use reuse the network stack "
  727. "of another service that is not running." % (self.id))
  728. return None
  729. # Names
  730. def build_container_name(project, service, number, one_off=False):
  731. bits = [project, service]
  732. if one_off:
  733. bits.append('run')
  734. return '_'.join(bits + [str(number)])
  735. # Images
  736. def parse_repository_tag(repo_path):
  737. """Splits image identification into base image path, tag/digest
  738. and it's separator.
  739. Example:
  740. >>> parse_repository_tag('user/repo@sha256:digest')
  741. ('user/repo', 'sha256:digest', '@')
  742. >>> parse_repository_tag('user/repo:v1')
  743. ('user/repo', 'v1', ':')
  744. """
  745. tag_separator = ":"
  746. digest_separator = "@"
  747. if digest_separator in repo_path:
  748. repo, tag = repo_path.rsplit(digest_separator, 1)
  749. return repo, tag, digest_separator
  750. repo, tag = repo_path, ""
  751. if tag_separator in repo_path:
  752. repo, tag = repo_path.rsplit(tag_separator, 1)
  753. if "/" in tag:
  754. repo, tag = repo_path, ""
  755. return repo, tag, tag_separator
  756. # Volumes
  757. def merge_volume_bindings(volumes, previous_container):
  758. """Return a list of volume bindings for a container. Container data volumes
  759. are replaced by those from the previous container.
  760. """
  761. affinity = {}
  762. volume_bindings = dict(
  763. build_volume_binding(volume)
  764. for volume in volumes
  765. if volume.external)
  766. if previous_container:
  767. old_volumes = get_container_data_volumes(previous_container, volumes)
  768. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  769. volume_bindings.update(
  770. build_volume_binding(volume) for volume in old_volumes)
  771. if old_volumes:
  772. affinity = {'affinity:container': '=' + previous_container.id}
  773. return list(volume_bindings.values()), affinity
  774. def get_container_data_volumes(container, volumes_option):
  775. """Find the container data volumes that are in `volumes_option`, and return
  776. a mapping of volume bindings for those volumes.
  777. """
  778. volumes = []
  779. volumes_option = volumes_option or []
  780. container_mounts = dict(
  781. (mount['Destination'], mount)
  782. for mount in container.get('Mounts') or {}
  783. )
  784. image_volumes = [
  785. VolumeSpec.parse(volume)
  786. for volume in
  787. container.image_config['ContainerConfig'].get('Volumes') or {}
  788. ]
  789. for volume in set(volumes_option + image_volumes):
  790. # No need to preserve host volumes
  791. if volume.external:
  792. continue
  793. mount = container_mounts.get(volume.internal)
  794. # New volume, doesn't exist in the old container
  795. if not mount:
  796. continue
  797. # Volume was previously a host volume, now it's a container volume
  798. if not mount.get('Name'):
  799. continue
  800. # Copy existing volume from old container
  801. volume = volume._replace(external=mount['Name'])
  802. volumes.append(volume)
  803. return volumes
  804. def warn_on_masked_volume(volumes_option, container_volumes, service):
  805. container_volumes = dict(
  806. (volume.internal, volume.external)
  807. for volume in container_volumes)
  808. for volume in volumes_option:
  809. if (
  810. volume.external and
  811. volume.internal in container_volumes and
  812. container_volumes.get(volume.internal) != volume.external
  813. ):
  814. log.warn((
  815. "Service \"{service}\" is using volume \"{volume}\" from the "
  816. "previous container. Host mapping \"{host_path}\" has no effect. "
  817. "Remove the existing containers (with `docker-compose rm {service}`) "
  818. "to use the host volume mapping."
  819. ).format(
  820. service=service,
  821. volume=volume.internal,
  822. host_path=volume.external))
  823. def build_volume_binding(volume_spec):
  824. return volume_spec.internal, volume_spec.repr()
  825. def build_volume_from(volume_from_spec):
  826. """
  827. volume_from can be either a service or a container. We want to return the
  828. container.id and format it into a string complete with the mode.
  829. """
  830. if isinstance(volume_from_spec.source, Service):
  831. containers = volume_from_spec.source.containers(stopped=True)
  832. if not containers:
  833. return "{}:{}".format(
  834. volume_from_spec.source.create_container().id,
  835. volume_from_spec.mode)
  836. container = containers[0]
  837. return "{}:{}".format(container.id, volume_from_spec.mode)
  838. elif isinstance(volume_from_spec.source, Container):
  839. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  840. # Labels
  841. def build_container_labels(label_options, service_labels, number, config_hash):
  842. labels = dict(label_options or {})
  843. labels.update(label.split('=', 1) for label in service_labels)
  844. labels[LABEL_CONTAINER_NUMBER] = str(number)
  845. labels[LABEL_VERSION] = __version__
  846. if config_hash:
  847. log.debug("Added config hash: %s" % config_hash)
  848. labels[LABEL_CONFIG_HASH] = config_hash
  849. return labels
  850. # Ulimits
  851. def build_ulimits(ulimit_config):
  852. if not ulimit_config:
  853. return None
  854. ulimits = []
  855. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  856. if isinstance(soft_hard_values, six.integer_types):
  857. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  858. elif isinstance(soft_hard_values, dict):
  859. ulimit_dict = {'name': limit_name}
  860. ulimit_dict.update(soft_hard_values)
  861. ulimits.append(ulimit_dict)
  862. return ulimits
  863. def get_log_config(logging_dict):
  864. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  865. log_options = logging_dict.get('options', None) if logging_dict else None
  866. return LogConfig(
  867. type=log_driver,
  868. config=log_options
  869. )
  870. # TODO: remove once fix is available in docker-py
  871. def format_environment(environment):
  872. def format_env(key, value):
  873. if value is None:
  874. return key
  875. if isinstance(value, six.binary_type):
  876. value = value.decode('utf-8')
  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