service.py 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. connected_networks = container.get('NetworkSettings.Networks')
  350. for network in self.networks:
  351. if network in connected_networks:
  352. self.client.disconnect_container_from_network(
  353. container.id, network)
  354. self.client.connect_container_to_network(
  355. container.id, network,
  356. aliases=self._get_aliases(container),
  357. links=self._get_links(False),
  358. )
  359. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  360. for c in self.duplicate_containers():
  361. log.info('Removing %s' % c.name)
  362. c.stop(timeout=timeout)
  363. c.remove()
  364. def duplicate_containers(self):
  365. containers = sorted(
  366. self.containers(stopped=True),
  367. key=lambda c: c.get('Created'),
  368. )
  369. numbers = set()
  370. for c in containers:
  371. if c.number in numbers:
  372. yield c
  373. else:
  374. numbers.add(c.number)
  375. @property
  376. def config_hash(self):
  377. return json_hash(self.config_dict())
  378. def config_dict(self):
  379. return {
  380. 'options': self.options,
  381. 'image_id': self.image()['Id'],
  382. 'links': self.get_link_names(),
  383. 'net': self.net.id,
  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.net.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.net.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 Net(object):
  628. """A `standard` network mode (ex: host, bridge)"""
  629. service_name = None
  630. def __init__(self, net):
  631. self.net = net
  632. @property
  633. def id(self):
  634. return self.net
  635. mode = id
  636. class ContainerNet(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 ServiceNet(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. # Copy existing volume from old container
  729. volume = volume._replace(external=mount['Source'])
  730. volumes.append(volume)
  731. return volumes
  732. def warn_on_masked_volume(volumes_option, container_volumes, service):
  733. container_volumes = dict(
  734. (volume.internal, volume.external)
  735. for volume in container_volumes)
  736. for volume in volumes_option:
  737. if (
  738. volume.external and
  739. volume.internal in container_volumes and
  740. container_volumes.get(volume.internal) != volume.external
  741. ):
  742. log.warn((
  743. "Service \"{service}\" is using volume \"{volume}\" from the "
  744. "previous container. Host mapping \"{host_path}\" has no effect. "
  745. "Remove the existing containers (with `docker-compose rm {service}`) "
  746. "to use the host volume mapping."
  747. ).format(
  748. service=service,
  749. volume=volume.internal,
  750. host_path=volume.external))
  751. def build_volume_binding(volume_spec):
  752. return volume_spec.internal, volume_spec.repr()
  753. def build_volume_from(volume_from_spec):
  754. """
  755. volume_from can be either a service or a container. We want to return the
  756. container.id and format it into a string complete with the mode.
  757. """
  758. if isinstance(volume_from_spec.source, Service):
  759. containers = volume_from_spec.source.containers(stopped=True)
  760. if not containers:
  761. return "{}:{}".format(
  762. volume_from_spec.source.create_container().id,
  763. volume_from_spec.mode)
  764. container = containers[0]
  765. return "{}:{}".format(container.id, volume_from_spec.mode)
  766. elif isinstance(volume_from_spec.source, Container):
  767. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  768. # Labels
  769. def build_container_labels(label_options, service_labels, number, config_hash):
  770. labels = dict(label_options or {})
  771. labels.update(label.split('=', 1) for label in service_labels)
  772. labels[LABEL_CONTAINER_NUMBER] = str(number)
  773. labels[LABEL_VERSION] = __version__
  774. if config_hash:
  775. log.debug("Added config hash: %s" % config_hash)
  776. labels[LABEL_CONFIG_HASH] = config_hash
  777. return labels
  778. # Ulimits
  779. def build_ulimits(ulimit_config):
  780. if not ulimit_config:
  781. return None
  782. ulimits = []
  783. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  784. if isinstance(soft_hard_values, six.integer_types):
  785. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  786. elif isinstance(soft_hard_values, dict):
  787. ulimit_dict = {'name': limit_name}
  788. ulimit_dict.update(soft_hard_values)
  789. ulimits.append(ulimit_dict)
  790. return ulimits
  791. def get_log_config(logging_dict):
  792. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  793. log_options = logging_dict.get('options', None) if logging_dict else None
  794. return LogConfig(
  795. type=log_driver,
  796. config=log_options
  797. )