service.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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 collections import OrderedDict
  9. from operator import attrgetter
  10. import enum
  11. import six
  12. from docker.errors import APIError
  13. from docker.errors import ImageNotFound
  14. from docker.errors import NotFound
  15. from docker.types import LogConfig
  16. from docker.types import Mount
  17. from docker.utils import version_gte
  18. from docker.utils import version_lt
  19. from docker.utils.ports import build_port_bindings
  20. from docker.utils.ports import split_port
  21. from docker.utils.utils import convert_tmpfs_mounts
  22. from . import __version__
  23. from . import const
  24. from . import progress_stream
  25. from .config import DOCKER_CONFIG_KEYS
  26. from .config import merge_environment
  27. from .config import merge_labels
  28. from .config.errors import DependencyError
  29. from .config.types import MountSpec
  30. from .config.types import ServicePort
  31. from .config.types import VolumeSpec
  32. from .const import DEFAULT_TIMEOUT
  33. from .const import IS_WINDOWS_PLATFORM
  34. from .const import LABEL_CONFIG_HASH
  35. from .const import LABEL_CONTAINER_NUMBER
  36. from .const import LABEL_ONE_OFF
  37. from .const import LABEL_PROJECT
  38. from .const import LABEL_SERVICE
  39. from .const import LABEL_VERSION
  40. from .const import NANOCPUS_SCALE
  41. from .container import Container
  42. from .errors import HealthCheckFailed
  43. from .errors import NoHealthCheckConfigured
  44. from .errors import OperationFailedError
  45. from .parallel import parallel_execute
  46. from .progress_stream import stream_output
  47. from .progress_stream import StreamOutputError
  48. from .utils import json_hash
  49. from .utils import parse_bytes
  50. from .utils import parse_seconds_float
  51. log = logging.getLogger(__name__)
  52. HOST_CONFIG_KEYS = [
  53. 'cap_add',
  54. 'cap_drop',
  55. 'cgroup_parent',
  56. 'cpu_count',
  57. 'cpu_percent',
  58. 'cpu_period',
  59. 'cpu_quota',
  60. 'cpu_shares',
  61. 'cpus',
  62. 'cpuset',
  63. 'device_cgroup_rules',
  64. 'devices',
  65. 'dns',
  66. 'dns_search',
  67. 'dns_opt',
  68. 'env_file',
  69. 'extra_hosts',
  70. 'group_add',
  71. 'init',
  72. 'ipc',
  73. 'read_only',
  74. 'log_driver',
  75. 'log_opt',
  76. 'mem_limit',
  77. 'mem_reservation',
  78. 'memswap_limit',
  79. 'mem_swappiness',
  80. 'oom_kill_disable',
  81. 'oom_score_adj',
  82. 'pid',
  83. 'pids_limit',
  84. 'privileged',
  85. 'restart',
  86. 'runtime',
  87. 'security_opt',
  88. 'shm_size',
  89. 'storage_opt',
  90. 'sysctls',
  91. 'userns_mode',
  92. 'volumes_from',
  93. 'volume_driver',
  94. ]
  95. CONDITION_STARTED = 'service_started'
  96. CONDITION_HEALTHY = 'service_healthy'
  97. class BuildError(Exception):
  98. def __init__(self, service, reason):
  99. self.service = service
  100. self.reason = reason
  101. class NeedsBuildError(Exception):
  102. def __init__(self, service):
  103. self.service = service
  104. class NoSuchImageError(Exception):
  105. pass
  106. ServiceName = namedtuple('ServiceName', 'project service number')
  107. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  108. @enum.unique
  109. class ConvergenceStrategy(enum.Enum):
  110. """Enumeration for all possible convergence strategies. Values refer to
  111. when containers should be recreated.
  112. """
  113. changed = 1
  114. always = 2
  115. never = 3
  116. @property
  117. def allows_recreate(self):
  118. return self is not type(self).never
  119. @enum.unique
  120. class ImageType(enum.Enum):
  121. """Enumeration for the types of images known to compose."""
  122. none = 0
  123. local = 1
  124. all = 2
  125. @enum.unique
  126. class BuildAction(enum.Enum):
  127. """Enumeration for the possible build actions."""
  128. none = 0
  129. force = 1
  130. skip = 2
  131. class Service(object):
  132. def __init__(
  133. self,
  134. name,
  135. client=None,
  136. project='default',
  137. use_networking=False,
  138. links=None,
  139. volumes_from=None,
  140. network_mode=None,
  141. networks=None,
  142. secrets=None,
  143. scale=None,
  144. pid_mode=None,
  145. **options
  146. ):
  147. self.name = name
  148. self.client = client
  149. self.project = project
  150. self.use_networking = use_networking
  151. self.links = links or []
  152. self.volumes_from = volumes_from or []
  153. self.network_mode = network_mode or NetworkMode(None)
  154. self.pid_mode = pid_mode or PidMode(None)
  155. self.networks = networks or {}
  156. self.secrets = secrets or []
  157. self.scale_num = scale or 1
  158. self.options = options
  159. def __repr__(self):
  160. return '<Service: {}>'.format(self.name)
  161. def containers(self, stopped=False, one_off=False, filters={}):
  162. filters.update({'label': self.labels(one_off=one_off)})
  163. return list(filter(None, [
  164. Container.from_ps(self.client, container)
  165. for container in self.client.containers(
  166. all=stopped,
  167. filters=filters)]))
  168. def get_container(self, number=1):
  169. """Return a :class:`compose.container.Container` for this service. The
  170. container must be active, and match `number`.
  171. """
  172. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  173. for container in self.client.containers(filters={'label': labels}):
  174. return Container.from_ps(self.client, container)
  175. raise ValueError("No container found for %s_%s" % (self.name, number))
  176. def start(self, **options):
  177. containers = self.containers(stopped=True)
  178. for c in containers:
  179. self.start_container_if_stopped(c, **options)
  180. return containers
  181. def show_scale_warnings(self, desired_num):
  182. if self.custom_container_name and desired_num > 1:
  183. log.warn('The "%s" service is using the custom container name "%s". '
  184. 'Docker requires each container to have a unique name. '
  185. 'Remove the custom name to scale the service.'
  186. % (self.name, self.custom_container_name))
  187. if self.specifies_host_port() and desired_num > 1:
  188. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  189. 'for this service are created on a single host, the port will clash.'
  190. % self.name)
  191. def scale(self, desired_num, timeout=None):
  192. """
  193. Adjusts the number of containers to the specified number and ensures
  194. they are running.
  195. - creates containers until there are at least `desired_num`
  196. - stops containers until there are at most `desired_num` running
  197. - starts containers until there are at least `desired_num` running
  198. - removes all stopped containers
  199. """
  200. self.show_scale_warnings(desired_num)
  201. running_containers = self.containers(stopped=False)
  202. num_running = len(running_containers)
  203. if desired_num == num_running:
  204. # do nothing as we already have the desired number
  205. log.info('Desired container number already achieved')
  206. return
  207. if desired_num > num_running:
  208. all_containers = self.containers(stopped=True)
  209. if num_running != len(all_containers):
  210. # we have some stopped containers, check for divergences
  211. stopped_containers = [
  212. c for c in all_containers if not c.is_running
  213. ]
  214. # Remove containers that have diverged
  215. divergent_containers = [
  216. c for c in stopped_containers if self._containers_have_diverged([c])
  217. ]
  218. for c in divergent_containers:
  219. c.remove()
  220. all_containers = list(set(all_containers) - set(divergent_containers))
  221. sorted_containers = sorted(all_containers, key=attrgetter('number'))
  222. self._execute_convergence_start(
  223. sorted_containers, desired_num, timeout, True, True
  224. )
  225. if desired_num < num_running:
  226. num_to_stop = num_running - desired_num
  227. sorted_running_containers = sorted(
  228. running_containers,
  229. key=attrgetter('number'))
  230. self._downscale(sorted_running_containers[-num_to_stop:], timeout)
  231. def create_container(self,
  232. one_off=False,
  233. previous_container=None,
  234. number=None,
  235. quiet=False,
  236. **override_options):
  237. """
  238. Create a container for this service. If the image doesn't exist, attempt to pull
  239. it.
  240. """
  241. # This is only necessary for `scale` and `volumes_from`
  242. # auto-creating containers to satisfy the dependency.
  243. self.ensure_image_exists()
  244. container_options = self._get_container_create_options(
  245. override_options,
  246. number or self._next_container_number(one_off=one_off),
  247. one_off=one_off,
  248. previous_container=previous_container,
  249. )
  250. if 'name' in container_options and not quiet:
  251. log.info("Creating %s" % container_options['name'])
  252. try:
  253. return Container.create(self.client, **container_options)
  254. except APIError as ex:
  255. raise OperationFailedError("Cannot create container for service %s: %s" %
  256. (self.name, ex.explanation))
  257. def ensure_image_exists(self, do_build=BuildAction.none, silent=False):
  258. if self.can_be_built() and do_build == BuildAction.force:
  259. self.build()
  260. return
  261. try:
  262. self.image()
  263. return
  264. except NoSuchImageError:
  265. pass
  266. if not self.can_be_built():
  267. self.pull(silent=silent)
  268. return
  269. if do_build == BuildAction.skip:
  270. raise NeedsBuildError(self)
  271. self.build()
  272. log.warn(
  273. "Image for service {} was built because it did not already exist. To "
  274. "rebuild this image you must use `docker-compose build` or "
  275. "`docker-compose up --build`.".format(self.name))
  276. def image(self):
  277. try:
  278. return self.client.inspect_image(self.image_name)
  279. except ImageNotFound:
  280. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  281. @property
  282. def image_name(self):
  283. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  284. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  285. containers = self.containers(stopped=True)
  286. if not containers:
  287. return ConvergencePlan('create', [])
  288. if strategy is ConvergenceStrategy.never:
  289. return ConvergencePlan('start', containers)
  290. if (
  291. strategy is ConvergenceStrategy.always or
  292. self._containers_have_diverged(containers)
  293. ):
  294. return ConvergencePlan('recreate', containers)
  295. stopped = [c for c in containers if not c.is_running]
  296. if stopped:
  297. return ConvergencePlan('start', stopped)
  298. return ConvergencePlan('noop', containers)
  299. def _containers_have_diverged(self, containers):
  300. config_hash = None
  301. try:
  302. config_hash = self.config_hash
  303. except NoSuchImageError as e:
  304. log.debug(
  305. 'Service %s has diverged: %s',
  306. self.name, six.text_type(e),
  307. )
  308. return True
  309. has_diverged = False
  310. for c in containers:
  311. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  312. if container_config_hash != config_hash:
  313. log.debug(
  314. '%s has diverged: %s != %s',
  315. c.name, container_config_hash, config_hash,
  316. )
  317. has_diverged = True
  318. return has_diverged
  319. def _execute_convergence_create(self, scale, detached, start, project_services=None):
  320. i = self._next_container_number()
  321. def create_and_start(service, n):
  322. container = service.create_container(number=n, quiet=True)
  323. if not detached:
  324. container.attach_log_stream()
  325. if start:
  326. self.start_container(container)
  327. return container
  328. containers, errors = parallel_execute(
  329. [ServiceName(self.project, self.name, index) for index in range(i, i + scale)],
  330. lambda service_name: create_and_start(self, service_name.number),
  331. lambda service_name: self.get_container_name(service_name.service, service_name.number),
  332. "Creating",
  333. parent_objects=project_services
  334. )
  335. for error in errors.values():
  336. raise OperationFailedError(error)
  337. return containers
  338. def _execute_convergence_recreate(self, containers, scale, timeout, detached, start,
  339. renew_anonymous_volumes):
  340. if scale is not None and len(containers) > scale:
  341. self._downscale(containers[scale:], timeout)
  342. containers = containers[:scale]
  343. def recreate(container):
  344. return self.recreate_container(
  345. container, timeout=timeout, attach_logs=not detached,
  346. start_new_container=start, renew_anonymous_volumes=renew_anonymous_volumes
  347. )
  348. containers, errors = parallel_execute(
  349. containers,
  350. recreate,
  351. lambda c: c.name,
  352. "Recreating",
  353. )
  354. for error in errors.values():
  355. raise OperationFailedError(error)
  356. if scale is not None and len(containers) < scale:
  357. containers.extend(self._execute_convergence_create(
  358. scale - len(containers), detached, start
  359. ))
  360. return containers
  361. def _execute_convergence_start(self, containers, scale, timeout, detached, start):
  362. if scale is not None and len(containers) > scale:
  363. self._downscale(containers[scale:], timeout)
  364. containers = containers[:scale]
  365. if start:
  366. _, errors = parallel_execute(
  367. containers,
  368. lambda c: self.start_container_if_stopped(c, attach_logs=not detached, quiet=True),
  369. lambda c: c.name,
  370. "Starting",
  371. )
  372. for error in errors.values():
  373. raise OperationFailedError(error)
  374. if scale is not None and len(containers) < scale:
  375. containers.extend(self._execute_convergence_create(
  376. scale - len(containers), detached, start
  377. ))
  378. return containers
  379. def _downscale(self, containers, timeout=None):
  380. def stop_and_remove(container):
  381. container.stop(timeout=self.stop_timeout(timeout))
  382. container.remove()
  383. parallel_execute(
  384. containers,
  385. stop_and_remove,
  386. lambda c: c.name,
  387. "Stopping and removing",
  388. )
  389. def execute_convergence_plan(self, plan, timeout=None, detached=False,
  390. start=True, scale_override=None,
  391. rescale=True, project_services=None,
  392. reset_container_image=False, renew_anonymous_volumes=False):
  393. (action, containers) = plan
  394. scale = scale_override if scale_override is not None else self.scale_num
  395. containers = sorted(containers, key=attrgetter('number'))
  396. self.show_scale_warnings(scale)
  397. if action == 'create':
  398. return self._execute_convergence_create(
  399. scale, detached, start, project_services
  400. )
  401. # The create action needs always needs an initial scale, but otherwise,
  402. # we set scale to none in no-rescale scenarios (`run` dependencies)
  403. if not rescale:
  404. scale = None
  405. if action == 'recreate':
  406. if reset_container_image:
  407. # Updating the image ID on the container object lets us recover old volumes if
  408. # the new image uses them as well
  409. img_id = self.image()['Id']
  410. for c in containers:
  411. c.reset_image(img_id)
  412. return self._execute_convergence_recreate(
  413. containers, scale, timeout, detached, start,
  414. renew_anonymous_volumes,
  415. )
  416. if action == 'start':
  417. return self._execute_convergence_start(
  418. containers, scale, timeout, detached, start
  419. )
  420. if action == 'noop':
  421. if scale != len(containers):
  422. return self._execute_convergence_start(
  423. containers, scale, timeout, detached, start
  424. )
  425. for c in containers:
  426. log.info("%s is up-to-date" % c.name)
  427. return containers
  428. raise Exception("Invalid action: {}".format(action))
  429. def recreate_container(self, container, timeout=None, attach_logs=False, start_new_container=True,
  430. renew_anonymous_volumes=False):
  431. """Recreate a container.
  432. The original container is renamed to a temporary name so that data
  433. volumes can be copied to the new container, before the original
  434. container is removed.
  435. """
  436. container.stop(timeout=self.stop_timeout(timeout))
  437. container.rename_to_tmp_name()
  438. new_container = self.create_container(
  439. previous_container=container if not renew_anonymous_volumes else None,
  440. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  441. quiet=True,
  442. )
  443. if attach_logs:
  444. new_container.attach_log_stream()
  445. if start_new_container:
  446. self.start_container(new_container)
  447. container.remove()
  448. return new_container
  449. def stop_timeout(self, timeout):
  450. if timeout is not None:
  451. return timeout
  452. timeout = parse_seconds_float(self.options.get('stop_grace_period'))
  453. if timeout is not None:
  454. return timeout
  455. return DEFAULT_TIMEOUT
  456. def start_container_if_stopped(self, container, attach_logs=False, quiet=False):
  457. if not container.is_running:
  458. if not quiet:
  459. log.info("Starting %s" % container.name)
  460. if attach_logs:
  461. container.attach_log_stream()
  462. return self.start_container(container)
  463. def start_container(self, container, use_network_aliases=True):
  464. self.connect_container_to_networks(container, use_network_aliases)
  465. try:
  466. container.start()
  467. except APIError as ex:
  468. raise OperationFailedError("Cannot start service %s: %s" % (self.name, ex.explanation))
  469. return container
  470. @property
  471. def prioritized_networks(self):
  472. return OrderedDict(
  473. sorted(
  474. self.networks.items(),
  475. key=lambda t: t[1].get('priority') or 0, reverse=True
  476. )
  477. )
  478. def connect_container_to_networks(self, container, use_network_aliases=True):
  479. connected_networks = container.get('NetworkSettings.Networks')
  480. for network, netdefs in self.prioritized_networks.items():
  481. if network in connected_networks:
  482. if short_id_alias_exists(container, network):
  483. continue
  484. self.client.disconnect_container_from_network(container.id, network)
  485. aliases = self._get_aliases(netdefs, container) if use_network_aliases else []
  486. self.client.connect_container_to_network(
  487. container.id, network,
  488. aliases=aliases,
  489. ipv4_address=netdefs.get('ipv4_address', None),
  490. ipv6_address=netdefs.get('ipv6_address', None),
  491. links=self._get_links(False),
  492. link_local_ips=netdefs.get('link_local_ips', None),
  493. )
  494. def remove_duplicate_containers(self, timeout=None):
  495. for c in self.duplicate_containers():
  496. log.info('Removing %s' % c.name)
  497. c.stop(timeout=self.stop_timeout(timeout))
  498. c.remove()
  499. def duplicate_containers(self):
  500. containers = sorted(
  501. self.containers(stopped=True),
  502. key=lambda c: c.get('Created'),
  503. )
  504. numbers = set()
  505. for c in containers:
  506. if c.number in numbers:
  507. yield c
  508. else:
  509. numbers.add(c.number)
  510. @property
  511. def config_hash(self):
  512. return json_hash(self.config_dict())
  513. def config_dict(self):
  514. return {
  515. 'options': self.options,
  516. 'image_id': self.image()['Id'],
  517. 'links': self.get_link_names(),
  518. 'net': self.network_mode.id,
  519. 'networks': self.networks,
  520. 'volumes_from': [
  521. (v.source.name, v.mode)
  522. for v in self.volumes_from if isinstance(v.source, Service)
  523. ],
  524. }
  525. def get_dependency_names(self):
  526. net_name = self.network_mode.service_name
  527. pid_namespace = self.pid_mode.service_name
  528. return (
  529. self.get_linked_service_names() +
  530. self.get_volumes_from_names() +
  531. ([net_name] if net_name else []) +
  532. ([pid_namespace] if pid_namespace else []) +
  533. list(self.options.get('depends_on', {}).keys())
  534. )
  535. def get_dependency_configs(self):
  536. net_name = self.network_mode.service_name
  537. pid_namespace = self.pid_mode.service_name
  538. configs = dict(
  539. [(name, None) for name in self.get_linked_service_names()]
  540. )
  541. configs.update(dict(
  542. [(name, None) for name in self.get_volumes_from_names()]
  543. ))
  544. configs.update({net_name: None} if net_name else {})
  545. configs.update({pid_namespace: None} if pid_namespace else {})
  546. configs.update(self.options.get('depends_on', {}))
  547. for svc, config in self.options.get('depends_on', {}).items():
  548. if config['condition'] == CONDITION_STARTED:
  549. configs[svc] = lambda s: True
  550. elif config['condition'] == CONDITION_HEALTHY:
  551. configs[svc] = lambda s: s.is_healthy()
  552. else:
  553. # The config schema already prevents this, but it might be
  554. # bypassed if Compose is called programmatically.
  555. raise ValueError(
  556. 'depends_on condition "{}" is invalid.'.format(
  557. config['condition']
  558. )
  559. )
  560. return configs
  561. def get_linked_service_names(self):
  562. return [service.name for (service, _) in self.links]
  563. def get_link_names(self):
  564. return [(service.name, alias) for service, alias in self.links]
  565. def get_volumes_from_names(self):
  566. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  567. # TODO: this would benefit from github.com/docker/docker/pull/14699
  568. # to remove the need to inspect every container
  569. def _next_container_number(self, one_off=False):
  570. containers = filter(None, [
  571. Container.from_ps(self.client, container)
  572. for container in self.client.containers(
  573. all=True,
  574. filters={'label': self.labels(one_off=one_off)})
  575. ])
  576. numbers = [c.number for c in containers]
  577. return 1 if not numbers else max(numbers) + 1
  578. def _get_aliases(self, network, container=None):
  579. return list(
  580. {self.name} |
  581. ({container.short_id} if container else set()) |
  582. set(network.get('aliases', ()))
  583. )
  584. def build_default_networking_config(self):
  585. if not self.networks:
  586. return {}
  587. network = self.networks[self.network_mode.id]
  588. endpoint = {
  589. 'Aliases': self._get_aliases(network),
  590. 'IPAMConfig': {},
  591. }
  592. if network.get('ipv4_address'):
  593. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  594. if network.get('ipv6_address'):
  595. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  596. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  597. def _get_links(self, link_to_self):
  598. links = {}
  599. for service, link_name in self.links:
  600. for container in service.containers():
  601. links[link_name or service.name] = container.name
  602. links[container.name] = container.name
  603. links[container.name_without_project] = container.name
  604. if link_to_self:
  605. for container in self.containers():
  606. links[self.name] = container.name
  607. links[container.name] = container.name
  608. links[container.name_without_project] = container.name
  609. for external_link in self.options.get('external_links') or []:
  610. if ':' not in external_link:
  611. link_name = external_link
  612. else:
  613. external_link, link_name = external_link.split(':')
  614. links[link_name] = external_link
  615. return [
  616. (alias, container_name)
  617. for (container_name, alias) in links.items()
  618. ]
  619. def _get_volumes_from(self):
  620. return [build_volume_from(spec) for spec in self.volumes_from]
  621. def _get_container_create_options(
  622. self,
  623. override_options,
  624. number,
  625. one_off=False,
  626. previous_container=None):
  627. add_config_hash = (not one_off and not override_options)
  628. container_options = dict(
  629. (k, self.options[k])
  630. for k in DOCKER_CONFIG_KEYS if k in self.options)
  631. override_volumes = override_options.pop('volumes', [])
  632. container_options.update(override_options)
  633. if not container_options.get('name'):
  634. container_options['name'] = self.get_container_name(self.name, number, one_off)
  635. container_options.setdefault('detach', True)
  636. # If a qualified hostname was given, split it into an
  637. # unqualified hostname and a domainname unless domainname
  638. # was also given explicitly. This matches behavior
  639. # until Docker Engine 1.11.0 - Docker API 1.23.
  640. if (version_lt(self.client.api_version, '1.23') and
  641. 'hostname' in container_options and
  642. 'domainname' not in container_options and
  643. '.' in container_options['hostname']):
  644. parts = container_options['hostname'].partition('.')
  645. container_options['hostname'] = parts[0]
  646. container_options['domainname'] = parts[2]
  647. if (version_gte(self.client.api_version, '1.25') and
  648. 'stop_grace_period' in self.options):
  649. container_options['stop_timeout'] = self.stop_timeout(None)
  650. if 'ports' in container_options or 'expose' in self.options:
  651. container_options['ports'] = build_container_ports(
  652. formatted_ports(container_options.get('ports', [])),
  653. self.options)
  654. if 'volumes' in container_options or override_volumes:
  655. container_options['volumes'] = list(set(
  656. container_options.get('volumes', []) + override_volumes
  657. ))
  658. container_options['environment'] = merge_environment(
  659. self._parse_proxy_config(),
  660. merge_environment(
  661. self.options.get('environment'),
  662. override_options.get('environment')
  663. )
  664. )
  665. container_options['labels'] = merge_labels(
  666. self.options.get('labels'),
  667. override_options.get('labels'))
  668. container_options, override_options = self._build_container_volume_options(
  669. previous_container, container_options, override_options
  670. )
  671. container_options['image'] = self.image_name
  672. container_options['labels'] = build_container_labels(
  673. container_options.get('labels', {}),
  674. self.labels(one_off=one_off),
  675. number,
  676. self.config_hash if add_config_hash else None)
  677. # Delete options which are only used in HostConfig
  678. for key in HOST_CONFIG_KEYS:
  679. container_options.pop(key, None)
  680. container_options['host_config'] = self._get_container_host_config(
  681. override_options,
  682. one_off=one_off)
  683. networking_config = self.build_default_networking_config()
  684. if networking_config:
  685. container_options['networking_config'] = networking_config
  686. container_options['environment'] = format_environment(
  687. container_options['environment'])
  688. return container_options
  689. def _build_container_volume_options(self, previous_container, container_options, override_options):
  690. container_volumes = []
  691. container_mounts = []
  692. if 'volumes' in container_options:
  693. container_volumes = [
  694. v for v in container_options.get('volumes') if isinstance(v, VolumeSpec)
  695. ]
  696. container_mounts = [v for v in container_options.get('volumes') if isinstance(v, MountSpec)]
  697. binds, affinity = merge_volume_bindings(
  698. container_volumes, self.options.get('tmpfs') or [], previous_container,
  699. container_mounts
  700. )
  701. override_options['binds'] = binds
  702. container_options['environment'].update(affinity)
  703. container_options['volumes'] = dict((v.internal, {}) for v in container_volumes or {})
  704. if version_gte(self.client.api_version, '1.30'):
  705. override_options['mounts'] = [build_mount(v) for v in container_mounts] or None
  706. else:
  707. # Workaround for 3.2 format
  708. override_options['tmpfs'] = self.options.get('tmpfs') or []
  709. for m in container_mounts:
  710. if m.is_tmpfs:
  711. override_options['tmpfs'].append(m.target)
  712. else:
  713. override_options['binds'].append(m.legacy_repr())
  714. container_options['volumes'][m.target] = {}
  715. secret_volumes = self.get_secret_volumes()
  716. if secret_volumes:
  717. if version_lt(self.client.api_version, '1.30'):
  718. override_options['binds'].extend(v.legacy_repr() for v in secret_volumes)
  719. container_options['volumes'].update(
  720. (v.target, {}) for v in secret_volumes
  721. )
  722. else:
  723. override_options['mounts'] = override_options.get('mounts') or []
  724. override_options['mounts'].extend([build_mount(v) for v in secret_volumes])
  725. return container_options, override_options
  726. def _get_container_host_config(self, override_options, one_off=False):
  727. options = dict(self.options, **override_options)
  728. logging_dict = options.get('logging', None)
  729. blkio_config = convert_blkio_config(options.get('blkio_config', None))
  730. log_config = get_log_config(logging_dict)
  731. init_path = None
  732. if isinstance(options.get('init'), six.string_types):
  733. init_path = options.get('init')
  734. options['init'] = True
  735. security_opt = [
  736. o.value for o in options.get('security_opt')
  737. ] if options.get('security_opt') else None
  738. nano_cpus = None
  739. if 'cpus' in options:
  740. nano_cpus = int(options.get('cpus') * NANOCPUS_SCALE)
  741. return self.client.create_host_config(
  742. links=self._get_links(link_to_self=one_off),
  743. port_bindings=build_port_bindings(
  744. formatted_ports(options.get('ports', []))
  745. ),
  746. binds=options.get('binds'),
  747. volumes_from=self._get_volumes_from(),
  748. privileged=options.get('privileged', False),
  749. network_mode=self.network_mode.mode,
  750. devices=options.get('devices'),
  751. dns=options.get('dns'),
  752. dns_opt=options.get('dns_opt'),
  753. dns_search=options.get('dns_search'),
  754. restart_policy=options.get('restart'),
  755. runtime=options.get('runtime'),
  756. cap_add=options.get('cap_add'),
  757. cap_drop=options.get('cap_drop'),
  758. mem_limit=options.get('mem_limit'),
  759. mem_reservation=options.get('mem_reservation'),
  760. memswap_limit=options.get('memswap_limit'),
  761. ulimits=build_ulimits(options.get('ulimits')),
  762. log_config=log_config,
  763. extra_hosts=options.get('extra_hosts'),
  764. read_only=options.get('read_only'),
  765. pid_mode=self.pid_mode.mode,
  766. security_opt=security_opt,
  767. ipc_mode=options.get('ipc'),
  768. cgroup_parent=options.get('cgroup_parent'),
  769. cpu_quota=options.get('cpu_quota'),
  770. shm_size=options.get('shm_size'),
  771. sysctls=options.get('sysctls'),
  772. pids_limit=options.get('pids_limit'),
  773. tmpfs=options.get('tmpfs'),
  774. oom_kill_disable=options.get('oom_kill_disable'),
  775. oom_score_adj=options.get('oom_score_adj'),
  776. mem_swappiness=options.get('mem_swappiness'),
  777. group_add=options.get('group_add'),
  778. userns_mode=options.get('userns_mode'),
  779. init=options.get('init', None),
  780. init_path=init_path,
  781. isolation=options.get('isolation'),
  782. cpu_count=options.get('cpu_count'),
  783. cpu_percent=options.get('cpu_percent'),
  784. nano_cpus=nano_cpus,
  785. volume_driver=options.get('volume_driver'),
  786. cpuset_cpus=options.get('cpuset'),
  787. cpu_shares=options.get('cpu_shares'),
  788. storage_opt=options.get('storage_opt'),
  789. blkio_weight=blkio_config.get('weight'),
  790. blkio_weight_device=blkio_config.get('weight_device'),
  791. device_read_bps=blkio_config.get('device_read_bps'),
  792. device_read_iops=blkio_config.get('device_read_iops'),
  793. device_write_bps=blkio_config.get('device_write_bps'),
  794. device_write_iops=blkio_config.get('device_write_iops'),
  795. mounts=options.get('mounts'),
  796. device_cgroup_rules=options.get('device_cgroup_rules'),
  797. cpu_period=options.get('cpu_period'),
  798. )
  799. def get_secret_volumes(self):
  800. def build_spec(secret):
  801. target = secret['secret'].target
  802. if target is None:
  803. target = '{}/{}'.format(const.SECRETS_PATH, secret['secret'].source)
  804. elif not os.path.isabs(target):
  805. target = '{}/{}'.format(const.SECRETS_PATH, target)
  806. return MountSpec('bind', secret['file'], target, read_only=True)
  807. return [build_spec(secret) for secret in self.secrets]
  808. def build(self, no_cache=False, pull=False, force_rm=False, memory=None, build_args_override=None):
  809. log.info('Building %s' % self.name)
  810. build_opts = self.options.get('build', {})
  811. build_args = build_opts.get('args', {}).copy()
  812. if build_args_override:
  813. build_args.update(build_args_override)
  814. for k, v in self._parse_proxy_config().items():
  815. build_args.setdefault(k, v)
  816. # python2 os.stat() doesn't support unicode on some UNIX, so we
  817. # encode it to a bytestring to be safe
  818. path = build_opts.get('context')
  819. if not six.PY3 and not IS_WINDOWS_PLATFORM:
  820. path = path.encode('utf8')
  821. build_output = self.client.build(
  822. path=path,
  823. tag=self.image_name,
  824. rm=True,
  825. forcerm=force_rm,
  826. pull=pull,
  827. nocache=no_cache,
  828. dockerfile=build_opts.get('dockerfile', None),
  829. cache_from=build_opts.get('cache_from', None),
  830. labels=build_opts.get('labels', None),
  831. buildargs=build_args,
  832. network_mode=build_opts.get('network', None),
  833. target=build_opts.get('target', None),
  834. shmsize=parse_bytes(build_opts.get('shm_size')) if build_opts.get('shm_size') else None,
  835. extra_hosts=build_opts.get('extra_hosts', None),
  836. container_limits={
  837. 'memory': parse_bytes(memory) if memory else None
  838. },
  839. )
  840. try:
  841. all_events = stream_output(build_output, sys.stdout)
  842. except StreamOutputError as e:
  843. raise BuildError(self, six.text_type(e))
  844. # Ensure the HTTP connection is not reused for another
  845. # streaming command, as the Docker daemon can sometimes
  846. # complain about it
  847. self.client.close()
  848. image_id = None
  849. for event in all_events:
  850. if 'stream' in event:
  851. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  852. if match:
  853. image_id = match.group(1)
  854. if image_id is None:
  855. raise BuildError(self, event if all_events else 'Unknown')
  856. return image_id
  857. def can_be_built(self):
  858. return 'build' in self.options
  859. def labels(self, one_off=False):
  860. return [
  861. '{0}={1}'.format(LABEL_PROJECT, self.project),
  862. '{0}={1}'.format(LABEL_SERVICE, self.name),
  863. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  864. ]
  865. @property
  866. def custom_container_name(self):
  867. return self.options.get('container_name')
  868. def get_container_name(self, service_name, number, one_off=False):
  869. if self.custom_container_name and not one_off:
  870. return self.custom_container_name
  871. container_name = build_container_name(
  872. self.project, service_name, number, one_off,
  873. )
  874. ext_links_origins = [l.split(':')[0] for l in self.options.get('external_links', [])]
  875. if container_name in ext_links_origins:
  876. raise DependencyError(
  877. 'Service {0} has a self-referential external link: {1}'.format(
  878. self.name, container_name
  879. )
  880. )
  881. return container_name
  882. def remove_image(self, image_type):
  883. if not image_type or image_type == ImageType.none:
  884. return False
  885. if image_type == ImageType.local and self.options.get('image'):
  886. return False
  887. log.info("Removing image %s", self.image_name)
  888. try:
  889. self.client.remove_image(self.image_name)
  890. return True
  891. except APIError as e:
  892. log.error("Failed to remove image for service %s: %s", self.name, e)
  893. return False
  894. def specifies_host_port(self):
  895. def has_host_port(binding):
  896. if isinstance(binding, dict):
  897. external_bindings = binding.get('published')
  898. else:
  899. _, external_bindings = split_port(binding)
  900. # there are no external bindings
  901. if external_bindings is None:
  902. return False
  903. # we only need to check the first binding from the range
  904. external_binding = external_bindings[0]
  905. # non-tuple binding means there is a host port specified
  906. if not isinstance(external_binding, tuple):
  907. return True
  908. # extract actual host port from tuple of (host_ip, host_port)
  909. _, host_port = external_binding
  910. if host_port is not None:
  911. return True
  912. return False
  913. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  914. def pull(self, ignore_pull_failures=False, silent=False):
  915. if 'image' not in self.options:
  916. return
  917. repo, tag, separator = parse_repository_tag(self.options['image'])
  918. tag = tag or 'latest'
  919. if not silent:
  920. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  921. try:
  922. output = self.client.pull(repo, tag=tag, stream=True)
  923. if silent:
  924. with open(os.devnull, 'w') as devnull:
  925. return progress_stream.get_digest_from_pull(
  926. stream_output(output, devnull))
  927. else:
  928. return progress_stream.get_digest_from_pull(
  929. stream_output(output, sys.stdout))
  930. except (StreamOutputError, NotFound) as e:
  931. if not ignore_pull_failures:
  932. raise
  933. else:
  934. log.error(six.text_type(e))
  935. def push(self, ignore_push_failures=False):
  936. if 'image' not in self.options or 'build' not in self.options:
  937. return
  938. repo, tag, separator = parse_repository_tag(self.options['image'])
  939. tag = tag or 'latest'
  940. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  941. output = self.client.push(repo, tag=tag, stream=True)
  942. try:
  943. return progress_stream.get_digest_from_push(
  944. stream_output(output, sys.stdout))
  945. except StreamOutputError as e:
  946. if not ignore_push_failures:
  947. raise
  948. else:
  949. log.error(six.text_type(e))
  950. def is_healthy(self):
  951. """ Check that all containers for this service report healthy.
  952. Returns false if at least one healthcheck is pending.
  953. If an unhealthy container is detected, raise a HealthCheckFailed
  954. exception.
  955. """
  956. result = True
  957. for ctnr in self.containers():
  958. ctnr.inspect()
  959. status = ctnr.get('State.Health.Status')
  960. if status is None:
  961. raise NoHealthCheckConfigured(self.name)
  962. elif status == 'starting':
  963. result = False
  964. elif status == 'unhealthy':
  965. raise HealthCheckFailed(ctnr.short_id)
  966. return result
  967. def _parse_proxy_config(self):
  968. client = self.client
  969. if 'proxies' not in client._general_configs:
  970. return {}
  971. docker_host = getattr(client, '_original_base_url', client.base_url)
  972. proxy_config = client._general_configs['proxies'].get(
  973. docker_host, client._general_configs['proxies'].get('default')
  974. ) or {}
  975. permitted = {
  976. 'ftpProxy': 'FTP_PROXY',
  977. 'httpProxy': 'HTTP_PROXY',
  978. 'httpsProxy': 'HTTPS_PROXY',
  979. 'noProxy': 'NO_PROXY',
  980. }
  981. result = {}
  982. for k, v in proxy_config.items():
  983. if k not in permitted:
  984. continue
  985. result[permitted[k]] = result[permitted[k].lower()] = v
  986. return result
  987. def short_id_alias_exists(container, network):
  988. aliases = container.get(
  989. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  990. return container.short_id in aliases
  991. class PidMode(object):
  992. def __init__(self, mode):
  993. self._mode = mode
  994. @property
  995. def mode(self):
  996. return self._mode
  997. @property
  998. def service_name(self):
  999. return None
  1000. class ServicePidMode(PidMode):
  1001. def __init__(self, service):
  1002. self.service = service
  1003. @property
  1004. def service_name(self):
  1005. return self.service.name
  1006. @property
  1007. def mode(self):
  1008. containers = self.service.containers()
  1009. if containers:
  1010. return 'container:' + containers[0].id
  1011. log.warn(
  1012. "Service %s is trying to use reuse the PID namespace "
  1013. "of another service that is not running." % (self.service_name)
  1014. )
  1015. return None
  1016. class ContainerPidMode(PidMode):
  1017. def __init__(self, container):
  1018. self.container = container
  1019. self._mode = 'container:{}'.format(container.id)
  1020. class NetworkMode(object):
  1021. """A `standard` network mode (ex: host, bridge)"""
  1022. service_name = None
  1023. def __init__(self, network_mode):
  1024. self.network_mode = network_mode
  1025. @property
  1026. def id(self):
  1027. return self.network_mode
  1028. mode = id
  1029. class ContainerNetworkMode(object):
  1030. """A network mode that uses a container's network stack."""
  1031. service_name = None
  1032. def __init__(self, container):
  1033. self.container = container
  1034. @property
  1035. def id(self):
  1036. return self.container.id
  1037. @property
  1038. def mode(self):
  1039. return 'container:' + self.container.id
  1040. class ServiceNetworkMode(object):
  1041. """A network mode that uses a service's network stack."""
  1042. def __init__(self, service):
  1043. self.service = service
  1044. @property
  1045. def id(self):
  1046. return self.service.name
  1047. service_name = id
  1048. @property
  1049. def mode(self):
  1050. containers = self.service.containers()
  1051. if containers:
  1052. return 'container:' + containers[0].id
  1053. log.warn("Service %s is trying to use reuse the network stack "
  1054. "of another service that is not running." % (self.id))
  1055. return None
  1056. # Names
  1057. def build_container_name(project, service, number, one_off=False):
  1058. bits = [project, service]
  1059. if one_off:
  1060. bits.append('run')
  1061. return '_'.join(bits + [str(number)])
  1062. # Images
  1063. def parse_repository_tag(repo_path):
  1064. """Splits image identification into base image path, tag/digest
  1065. and it's separator.
  1066. Example:
  1067. >>> parse_repository_tag('user/repo@sha256:digest')
  1068. ('user/repo', 'sha256:digest', '@')
  1069. >>> parse_repository_tag('user/repo:v1')
  1070. ('user/repo', 'v1', ':')
  1071. """
  1072. tag_separator = ":"
  1073. digest_separator = "@"
  1074. if digest_separator in repo_path:
  1075. repo, tag = repo_path.rsplit(digest_separator, 1)
  1076. return repo, tag, digest_separator
  1077. repo, tag = repo_path, ""
  1078. if tag_separator in repo_path:
  1079. repo, tag = repo_path.rsplit(tag_separator, 1)
  1080. if "/" in tag:
  1081. repo, tag = repo_path, ""
  1082. return repo, tag, tag_separator
  1083. # Volumes
  1084. def merge_volume_bindings(volumes, tmpfs, previous_container, mounts):
  1085. """
  1086. Return a list of volume bindings for a container. Container data volumes
  1087. are replaced by those from the previous container.
  1088. Anonymous mounts are updated in place.
  1089. """
  1090. affinity = {}
  1091. volume_bindings = dict(
  1092. build_volume_binding(volume)
  1093. for volume in volumes
  1094. if volume.external
  1095. )
  1096. if previous_container:
  1097. old_volumes, old_mounts = get_container_data_volumes(
  1098. previous_container, volumes, tmpfs, mounts
  1099. )
  1100. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  1101. volume_bindings.update(
  1102. build_volume_binding(volume) for volume in old_volumes
  1103. )
  1104. if old_volumes or old_mounts:
  1105. affinity = {'affinity:container': '=' + previous_container.id}
  1106. return list(volume_bindings.values()), affinity
  1107. def get_container_data_volumes(container, volumes_option, tmpfs_option, mounts_option):
  1108. """
  1109. Find the container data volumes that are in `volumes_option`, and return
  1110. a mapping of volume bindings for those volumes.
  1111. Anonymous volume mounts are updated in place instead.
  1112. """
  1113. volumes = []
  1114. volumes_option = volumes_option or []
  1115. container_mounts = dict(
  1116. (mount['Destination'], mount)
  1117. for mount in container.get('Mounts') or {}
  1118. )
  1119. image_volumes = [
  1120. VolumeSpec.parse(volume)
  1121. for volume in
  1122. container.image_config['ContainerConfig'].get('Volumes') or {}
  1123. ]
  1124. for volume in set(volumes_option + image_volumes):
  1125. # No need to preserve host volumes
  1126. if volume.external:
  1127. continue
  1128. # Attempting to rebind tmpfs volumes breaks: https://github.com/docker/compose/issues/4751
  1129. if volume.internal in convert_tmpfs_mounts(tmpfs_option).keys():
  1130. continue
  1131. mount = container_mounts.get(volume.internal)
  1132. # New volume, doesn't exist in the old container
  1133. if not mount:
  1134. continue
  1135. # Volume was previously a host volume, now it's a container volume
  1136. if not mount.get('Name'):
  1137. continue
  1138. # Copy existing volume from old container
  1139. volume = volume._replace(external=mount['Name'])
  1140. volumes.append(volume)
  1141. updated_mounts = False
  1142. for mount in mounts_option:
  1143. if mount.type != 'volume':
  1144. continue
  1145. ctnr_mount = container_mounts.get(mount.target)
  1146. if not ctnr_mount or not ctnr_mount.get('Name'):
  1147. continue
  1148. mount.source = ctnr_mount['Name']
  1149. updated_mounts = True
  1150. return volumes, updated_mounts
  1151. def warn_on_masked_volume(volumes_option, container_volumes, service):
  1152. container_volumes = dict(
  1153. (volume.internal, volume.external)
  1154. for volume in container_volumes)
  1155. for volume in volumes_option:
  1156. if (
  1157. volume.external and
  1158. volume.internal in container_volumes and
  1159. container_volumes.get(volume.internal) != volume.external
  1160. ):
  1161. log.warn((
  1162. "Service \"{service}\" is using volume \"{volume}\" from the "
  1163. "previous container. Host mapping \"{host_path}\" has no effect. "
  1164. "Remove the existing containers (with `docker-compose rm {service}`) "
  1165. "to use the host volume mapping."
  1166. ).format(
  1167. service=service,
  1168. volume=volume.internal,
  1169. host_path=volume.external))
  1170. def build_volume_binding(volume_spec):
  1171. return volume_spec.internal, volume_spec.repr()
  1172. def build_volume_from(volume_from_spec):
  1173. """
  1174. volume_from can be either a service or a container. We want to return the
  1175. container.id and format it into a string complete with the mode.
  1176. """
  1177. if isinstance(volume_from_spec.source, Service):
  1178. containers = volume_from_spec.source.containers(stopped=True)
  1179. if not containers:
  1180. return "{}:{}".format(
  1181. volume_from_spec.source.create_container().id,
  1182. volume_from_spec.mode)
  1183. container = containers[0]
  1184. return "{}:{}".format(container.id, volume_from_spec.mode)
  1185. elif isinstance(volume_from_spec.source, Container):
  1186. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  1187. def build_mount(mount_spec):
  1188. kwargs = {}
  1189. if mount_spec.options:
  1190. for option, sdk_name in mount_spec.options_map[mount_spec.type].items():
  1191. if option in mount_spec.options:
  1192. kwargs[sdk_name] = mount_spec.options[option]
  1193. return Mount(
  1194. type=mount_spec.type, target=mount_spec.target, source=mount_spec.source,
  1195. read_only=mount_spec.read_only, consistency=mount_spec.consistency, **kwargs
  1196. )
  1197. # Labels
  1198. def build_container_labels(label_options, service_labels, number, config_hash):
  1199. labels = dict(label_options or {})
  1200. labels.update(label.split('=', 1) for label in service_labels)
  1201. labels[LABEL_CONTAINER_NUMBER] = str(number)
  1202. labels[LABEL_VERSION] = __version__
  1203. if config_hash:
  1204. log.debug("Added config hash: %s" % config_hash)
  1205. labels[LABEL_CONFIG_HASH] = config_hash
  1206. return labels
  1207. # Ulimits
  1208. def build_ulimits(ulimit_config):
  1209. if not ulimit_config:
  1210. return None
  1211. ulimits = []
  1212. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  1213. if isinstance(soft_hard_values, six.integer_types):
  1214. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  1215. elif isinstance(soft_hard_values, dict):
  1216. ulimit_dict = {'name': limit_name}
  1217. ulimit_dict.update(soft_hard_values)
  1218. ulimits.append(ulimit_dict)
  1219. return ulimits
  1220. def get_log_config(logging_dict):
  1221. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  1222. log_options = logging_dict.get('options', None) if logging_dict else None
  1223. return LogConfig(
  1224. type=log_driver,
  1225. config=log_options
  1226. )
  1227. # TODO: remove once fix is available in docker-py
  1228. def format_environment(environment):
  1229. def format_env(key, value):
  1230. if value is None:
  1231. return key
  1232. if isinstance(value, six.binary_type):
  1233. value = value.decode('utf-8')
  1234. return '{key}={value}'.format(key=key, value=value)
  1235. return [format_env(*item) for item in environment.items()]
  1236. # Ports
  1237. def formatted_ports(ports):
  1238. result = []
  1239. for port in ports:
  1240. if isinstance(port, ServicePort):
  1241. result.append(port.legacy_repr())
  1242. else:
  1243. result.append(port)
  1244. return result
  1245. def build_container_ports(container_ports, options):
  1246. ports = []
  1247. all_ports = container_ports + options.get('expose', [])
  1248. for port_range in all_ports:
  1249. internal_range, _ = split_port(port_range)
  1250. for port in internal_range:
  1251. port = str(port)
  1252. if '/' in port:
  1253. port = tuple(port.split('/'))
  1254. ports.append(port)
  1255. return ports
  1256. def convert_blkio_config(blkio_config):
  1257. result = {}
  1258. if blkio_config is None:
  1259. return result
  1260. result['weight'] = blkio_config.get('weight')
  1261. for field in [
  1262. "device_read_bps", "device_read_iops", "device_write_bps",
  1263. "device_write_iops", "weight_device",
  1264. ]:
  1265. if field not in blkio_config:
  1266. continue
  1267. arr = []
  1268. for item in blkio_config[field]:
  1269. arr.append(dict([(k.capitalize(), v) for k, v in item.items()]))
  1270. result[field] = arr
  1271. return result