service.py 51 KB

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