service.py 53 KB

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