service.py 51 KB

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