service.py 50 KB

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