service.py 32 KB

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