service.py 51 KB

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