service.py 52 KB

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