service.py 50 KB

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