service.py 33 KB

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