service.py 37 KB

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