service.py 52 KB

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