service.py 32 KB

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