service.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  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_shares',
  61. 'cpus',
  62. 'cpuset',
  63. 'device_cgroup_rules',
  64. 'devices',
  65. 'dns',
  66. 'dns_search',
  67. 'dns_opt',
  68. 'env_file',
  69. 'extra_hosts',
  70. 'group_add',
  71. 'init',
  72. 'ipc',
  73. 'read_only',
  74. 'log_driver',
  75. 'log_opt',
  76. 'mem_limit',
  77. 'mem_reservation',
  78. 'memswap_limit',
  79. 'mem_swappiness',
  80. 'oom_kill_disable',
  81. 'oom_score_adj',
  82. 'pid',
  83. 'pids_limit',
  84. 'privileged',
  85. 'restart',
  86. 'runtime',
  87. 'security_opt',
  88. 'shm_size',
  89. 'storage_opt',
  90. 'sysctls',
  91. 'userns_mode',
  92. 'volumes_from',
  93. 'volume_driver',
  94. ]
  95. CONDITION_STARTED = 'service_started'
  96. CONDITION_HEALTHY = 'service_healthy'
  97. class BuildError(Exception):
  98. def __init__(self, service, reason):
  99. self.service = service
  100. self.reason = reason
  101. class NeedsBuildError(Exception):
  102. def __init__(self, service):
  103. self.service = service
  104. class NoSuchImageError(Exception):
  105. pass
  106. ServiceName = namedtuple('ServiceName', 'project service number')
  107. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  108. @enum.unique
  109. class ConvergenceStrategy(enum.Enum):
  110. """Enumeration for all possible convergence strategies. Values refer to
  111. when containers should be recreated.
  112. """
  113. changed = 1
  114. always = 2
  115. never = 3
  116. @property
  117. def allows_recreate(self):
  118. return self is not type(self).never
  119. @enum.unique
  120. class ImageType(enum.Enum):
  121. """Enumeration for the types of images known to compose."""
  122. none = 0
  123. local = 1
  124. all = 2
  125. @enum.unique
  126. class BuildAction(enum.Enum):
  127. """Enumeration for the possible build actions."""
  128. none = 0
  129. force = 1
  130. skip = 2
  131. class Service(object):
  132. def __init__(
  133. self,
  134. name,
  135. client=None,
  136. project='default',
  137. use_networking=False,
  138. links=None,
  139. volumes_from=None,
  140. network_mode=None,
  141. networks=None,
  142. secrets=None,
  143. scale=None,
  144. pid_mode=None,
  145. **options
  146. ):
  147. self.name = name
  148. self.client = client
  149. self.project = project
  150. self.use_networking = use_networking
  151. self.links = links or []
  152. self.volumes_from = volumes_from or []
  153. self.network_mode = network_mode or NetworkMode(None)
  154. self.pid_mode = pid_mode or PidMode(None)
  155. self.networks = networks or {}
  156. self.secrets = secrets or []
  157. self.scale_num = scale or 1
  158. self.options = options
  159. def __repr__(self):
  160. return '<Service: {}>'.format(self.name)
  161. def containers(self, stopped=False, one_off=False, filters={}):
  162. filters.update({'label': self.labels(one_off=one_off)})
  163. return list(filter(None, [
  164. Container.from_ps(self.client, container)
  165. for container in self.client.containers(
  166. all=stopped,
  167. filters=filters)]))
  168. def get_container(self, number=1):
  169. """Return a :class:`compose.container.Container` for this service. The
  170. container must be active, and match `number`.
  171. """
  172. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  173. for container in self.client.containers(filters={'label': labels}):
  174. return Container.from_ps(self.client, container)
  175. raise ValueError("No container found for %s_%s" % (self.name, number))
  176. def start(self, **options):
  177. containers = self.containers(stopped=True)
  178. for c in containers:
  179. self.start_container_if_stopped(c, **options)
  180. return containers
  181. def show_scale_warnings(self, desired_num):
  182. if self.custom_container_name and desired_num > 1:
  183. log.warn('The "%s" service is using the custom container name "%s". '
  184. 'Docker requires each container to have a unique name. '
  185. 'Remove the custom name to scale the service.'
  186. % (self.name, self.custom_container_name))
  187. if self.specifies_host_port() and desired_num > 1:
  188. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  189. 'for this service are created on a single host, the port will clash.'
  190. % self.name)
  191. def scale(self, desired_num, timeout=None):
  192. """
  193. Adjusts the number of containers to the specified number and ensures
  194. they are running.
  195. - creates containers until there are at least `desired_num`
  196. - stops containers until there are at most `desired_num` running
  197. - starts containers until there are at least `desired_num` running
  198. - removes all stopped containers
  199. """
  200. self.show_scale_warnings(desired_num)
  201. running_containers = self.containers(stopped=False)
  202. num_running = len(running_containers)
  203. if desired_num == num_running:
  204. # do nothing as we already have the desired number
  205. log.info('Desired container number already achieved')
  206. return
  207. if desired_num > num_running:
  208. all_containers = self.containers(stopped=True)
  209. if num_running != len(all_containers):
  210. # we have some stopped containers, check for divergences
  211. stopped_containers = [
  212. c for c in all_containers if not c.is_running
  213. ]
  214. # Remove containers that have diverged
  215. divergent_containers = [
  216. c for c in stopped_containers if self._containers_have_diverged([c])
  217. ]
  218. for c in divergent_containers:
  219. c.remove()
  220. all_containers = list(set(all_containers) - set(divergent_containers))
  221. sorted_containers = sorted(all_containers, key=attrgetter('number'))
  222. self._execute_convergence_start(
  223. sorted_containers, desired_num, timeout, True, True
  224. )
  225. if desired_num < num_running:
  226. num_to_stop = num_running - desired_num
  227. sorted_running_containers = sorted(
  228. running_containers,
  229. key=attrgetter('number'))
  230. self._downscale(sorted_running_containers[-num_to_stop:], timeout)
  231. def create_container(self,
  232. one_off=False,
  233. previous_container=None,
  234. number=None,
  235. quiet=False,
  236. **override_options):
  237. """
  238. Create a container for this service. If the image doesn't exist, attempt to pull
  239. it.
  240. """
  241. # This is only necessary for `scale` and `volumes_from`
  242. # auto-creating containers to satisfy the dependency.
  243. self.ensure_image_exists()
  244. container_options = self._get_container_create_options(
  245. override_options,
  246. number or self._next_container_number(one_off=one_off),
  247. one_off=one_off,
  248. previous_container=previous_container,
  249. )
  250. if 'name' in container_options and not quiet:
  251. log.info("Creating %s" % container_options['name'])
  252. try:
  253. return Container.create(self.client, **container_options)
  254. except APIError as ex:
  255. raise OperationFailedError("Cannot create container for service %s: %s" %
  256. (self.name, ex.explanation))
  257. def ensure_image_exists(self, do_build=BuildAction.none, silent=False):
  258. if self.can_be_built() and do_build == BuildAction.force:
  259. self.build()
  260. return
  261. try:
  262. self.image()
  263. return
  264. except NoSuchImageError:
  265. pass
  266. if not self.can_be_built():
  267. self.pull(silent=silent)
  268. return
  269. if do_build == BuildAction.skip:
  270. raise NeedsBuildError(self)
  271. self.build()
  272. log.warn(
  273. "Image for service {} was built because it did not already exist. To "
  274. "rebuild this image you must use `docker-compose build` or "
  275. "`docker-compose up --build`.".format(self.name))
  276. def image(self):
  277. try:
  278. return self.client.inspect_image(self.image_name)
  279. except ImageNotFound:
  280. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  281. @property
  282. def image_name(self):
  283. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  284. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  285. containers = self.containers(stopped=True)
  286. if not containers:
  287. return ConvergencePlan('create', [])
  288. if strategy is ConvergenceStrategy.never:
  289. return ConvergencePlan('start', containers)
  290. if (
  291. strategy is ConvergenceStrategy.always or
  292. self._containers_have_diverged(containers)
  293. ):
  294. return ConvergencePlan('recreate', containers)
  295. stopped = [c for c in containers if not c.is_running]
  296. if stopped:
  297. return ConvergencePlan('start', stopped)
  298. return ConvergencePlan('noop', containers)
  299. def _containers_have_diverged(self, containers):
  300. config_hash = None
  301. try:
  302. config_hash = self.config_hash
  303. except NoSuchImageError as e:
  304. log.debug(
  305. 'Service %s has diverged: %s',
  306. self.name, six.text_type(e),
  307. )
  308. return True
  309. has_diverged = False
  310. for c in containers:
  311. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  312. if container_config_hash != config_hash:
  313. log.debug(
  314. '%s has diverged: %s != %s',
  315. c.name, container_config_hash, config_hash,
  316. )
  317. has_diverged = True
  318. return has_diverged
  319. def _execute_convergence_create(self, scale, detached, start, project_services=None):
  320. i = self._next_container_number()
  321. def create_and_start(service, n):
  322. container = service.create_container(number=n, quiet=True)
  323. if not detached:
  324. container.attach_log_stream()
  325. if start:
  326. self.start_container(container)
  327. return container
  328. containers, errors = parallel_execute(
  329. [ServiceName(self.project, self.name, index) for index in range(i, i + scale)],
  330. lambda service_name: create_and_start(self, service_name.number),
  331. lambda service_name: self.get_container_name(service_name.service, service_name.number),
  332. "Creating"
  333. )
  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. cpu_period=options.get('cpu_period'),
  797. )
  798. def get_secret_volumes(self):
  799. def build_spec(secret):
  800. target = secret['secret'].target
  801. if target is None:
  802. target = '{}/{}'.format(const.SECRETS_PATH, secret['secret'].source)
  803. elif not os.path.isabs(target):
  804. target = '{}/{}'.format(const.SECRETS_PATH, target)
  805. return MountSpec('bind', secret['file'], target, read_only=True)
  806. return [build_spec(secret) for secret in self.secrets]
  807. def build(self, no_cache=False, pull=False, force_rm=False, memory=None, build_args_override=None):
  808. log.info('Building %s' % self.name)
  809. build_opts = self.options.get('build', {})
  810. build_args = build_opts.get('args', {}).copy()
  811. if build_args_override:
  812. build_args.update(build_args_override)
  813. for k, v in self._parse_proxy_config().items():
  814. build_args.setdefault(k, v)
  815. # python2 os.stat() doesn't support unicode on some UNIX, so we
  816. # encode it to a bytestring to be safe
  817. path = build_opts.get('context')
  818. if not six.PY3 and not IS_WINDOWS_PLATFORM:
  819. path = path.encode('utf8')
  820. build_output = self.client.build(
  821. path=path,
  822. tag=self.image_name,
  823. rm=True,
  824. forcerm=force_rm,
  825. pull=pull,
  826. nocache=no_cache,
  827. dockerfile=build_opts.get('dockerfile', None),
  828. cache_from=build_opts.get('cache_from', None),
  829. labels=build_opts.get('labels', None),
  830. buildargs=build_args,
  831. network_mode=build_opts.get('network', None),
  832. target=build_opts.get('target', None),
  833. shmsize=parse_bytes(build_opts.get('shm_size')) if build_opts.get('shm_size') else None,
  834. extra_hosts=build_opts.get('extra_hosts', None),
  835. container_limits={
  836. 'memory': parse_bytes(memory) if memory else None
  837. },
  838. )
  839. try:
  840. all_events = stream_output(build_output, sys.stdout)
  841. except StreamOutputError as e:
  842. raise BuildError(self, six.text_type(e))
  843. # Ensure the HTTP connection is not reused for another
  844. # streaming command, as the Docker daemon can sometimes
  845. # complain about it
  846. self.client.close()
  847. image_id = None
  848. for event in all_events:
  849. if 'stream' in event:
  850. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  851. if match:
  852. image_id = match.group(1)
  853. if image_id is None:
  854. raise BuildError(self, event if all_events else 'Unknown')
  855. return image_id
  856. def can_be_built(self):
  857. return 'build' in self.options
  858. def labels(self, one_off=False):
  859. return [
  860. '{0}={1}'.format(LABEL_PROJECT, self.project),
  861. '{0}={1}'.format(LABEL_SERVICE, self.name),
  862. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  863. ]
  864. @property
  865. def custom_container_name(self):
  866. return self.options.get('container_name')
  867. def get_container_name(self, service_name, number, one_off=False):
  868. if self.custom_container_name and not one_off:
  869. return self.custom_container_name
  870. container_name = build_container_name(
  871. self.project, service_name, number, one_off,
  872. )
  873. ext_links_origins = [l.split(':')[0] for l in self.options.get('external_links', [])]
  874. if container_name in ext_links_origins:
  875. raise DependencyError(
  876. 'Service {0} has a self-referential external link: {1}'.format(
  877. self.name, container_name
  878. )
  879. )
  880. return container_name
  881. def remove_image(self, image_type):
  882. if not image_type or image_type == ImageType.none:
  883. return False
  884. if image_type == ImageType.local and self.options.get('image'):
  885. return False
  886. log.info("Removing image %s", self.image_name)
  887. try:
  888. self.client.remove_image(self.image_name)
  889. return True
  890. except APIError as e:
  891. log.error("Failed to remove image for service %s: %s", self.name, e)
  892. return False
  893. def specifies_host_port(self):
  894. def has_host_port(binding):
  895. if isinstance(binding, dict):
  896. external_bindings = binding.get('published')
  897. else:
  898. _, external_bindings = split_port(binding)
  899. # there are no external bindings
  900. if external_bindings is None:
  901. return False
  902. # we only need to check the first binding from the range
  903. external_binding = external_bindings[0]
  904. # non-tuple binding means there is a host port specified
  905. if not isinstance(external_binding, tuple):
  906. return True
  907. # extract actual host port from tuple of (host_ip, host_port)
  908. _, host_port = external_binding
  909. if host_port is not None:
  910. return True
  911. return False
  912. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  913. def pull(self, ignore_pull_failures=False, silent=False):
  914. if 'image' not in self.options:
  915. return
  916. repo, tag, separator = parse_repository_tag(self.options['image'])
  917. tag = tag or 'latest'
  918. if not silent:
  919. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  920. try:
  921. output = self.client.pull(repo, tag=tag, stream=True)
  922. if silent:
  923. with open(os.devnull, 'w') as devnull:
  924. return progress_stream.get_digest_from_pull(
  925. stream_output(output, devnull))
  926. else:
  927. return progress_stream.get_digest_from_pull(
  928. stream_output(output, sys.stdout))
  929. except (StreamOutputError, NotFound) as e:
  930. if not ignore_pull_failures:
  931. raise
  932. else:
  933. log.error(six.text_type(e))
  934. def push(self, ignore_push_failures=False):
  935. if 'image' not in self.options or 'build' not in self.options:
  936. return
  937. repo, tag, separator = parse_repository_tag(self.options['image'])
  938. tag = tag or 'latest'
  939. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  940. output = self.client.push(repo, tag=tag, stream=True)
  941. try:
  942. return progress_stream.get_digest_from_push(
  943. stream_output(output, sys.stdout))
  944. except StreamOutputError as e:
  945. if not ignore_push_failures:
  946. raise
  947. else:
  948. log.error(six.text_type(e))
  949. def is_healthy(self):
  950. """ Check that all containers for this service report healthy.
  951. Returns false if at least one healthcheck is pending.
  952. If an unhealthy container is detected, raise a HealthCheckFailed
  953. exception.
  954. """
  955. result = True
  956. for ctnr in self.containers():
  957. ctnr.inspect()
  958. status = ctnr.get('State.Health.Status')
  959. if status is None:
  960. raise NoHealthCheckConfigured(self.name)
  961. elif status == 'starting':
  962. result = False
  963. elif status == 'unhealthy':
  964. raise HealthCheckFailed(ctnr.short_id)
  965. return result
  966. def _parse_proxy_config(self):
  967. client = self.client
  968. if 'proxies' not in client._general_configs:
  969. return {}
  970. docker_host = getattr(client, '_original_base_url', client.base_url)
  971. proxy_config = client._general_configs['proxies'].get(
  972. docker_host, client._general_configs['proxies'].get('default')
  973. ) or {}
  974. permitted = {
  975. 'ftpProxy': 'FTP_PROXY',
  976. 'httpProxy': 'HTTP_PROXY',
  977. 'httpsProxy': 'HTTPS_PROXY',
  978. 'noProxy': 'NO_PROXY',
  979. }
  980. result = {}
  981. for k, v in proxy_config.items():
  982. if k not in permitted:
  983. continue
  984. result[permitted[k]] = result[permitted[k].lower()] = v
  985. return result
  986. def short_id_alias_exists(container, network):
  987. aliases = container.get(
  988. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  989. return container.short_id in aliases
  990. class PidMode(object):
  991. def __init__(self, mode):
  992. self._mode = mode
  993. @property
  994. def mode(self):
  995. return self._mode
  996. @property
  997. def service_name(self):
  998. return None
  999. class ServicePidMode(PidMode):
  1000. def __init__(self, service):
  1001. self.service = service
  1002. @property
  1003. def service_name(self):
  1004. return self.service.name
  1005. @property
  1006. def mode(self):
  1007. containers = self.service.containers()
  1008. if containers:
  1009. return 'container:' + containers[0].id
  1010. log.warn(
  1011. "Service %s is trying to use reuse the PID namespace "
  1012. "of another service that is not running." % (self.service_name)
  1013. )
  1014. return None
  1015. class ContainerPidMode(PidMode):
  1016. def __init__(self, container):
  1017. self.container = container
  1018. self._mode = 'container:{}'.format(container.id)
  1019. class NetworkMode(object):
  1020. """A `standard` network mode (ex: host, bridge)"""
  1021. service_name = None
  1022. def __init__(self, network_mode):
  1023. self.network_mode = network_mode
  1024. @property
  1025. def id(self):
  1026. return self.network_mode
  1027. mode = id
  1028. class ContainerNetworkMode(object):
  1029. """A network mode that uses a container's network stack."""
  1030. service_name = None
  1031. def __init__(self, container):
  1032. self.container = container
  1033. @property
  1034. def id(self):
  1035. return self.container.id
  1036. @property
  1037. def mode(self):
  1038. return 'container:' + self.container.id
  1039. class ServiceNetworkMode(object):
  1040. """A network mode that uses a service's network stack."""
  1041. def __init__(self, service):
  1042. self.service = service
  1043. @property
  1044. def id(self):
  1045. return self.service.name
  1046. service_name = id
  1047. @property
  1048. def mode(self):
  1049. containers = self.service.containers()
  1050. if containers:
  1051. return 'container:' + containers[0].id
  1052. log.warn("Service %s is trying to use reuse the network stack "
  1053. "of another service that is not running." % (self.id))
  1054. return None
  1055. # Names
  1056. def build_container_name(project, service, number, one_off=False):
  1057. bits = [project, service]
  1058. if one_off:
  1059. bits.append('run')
  1060. return '_'.join(bits + [str(number)])
  1061. # Images
  1062. def parse_repository_tag(repo_path):
  1063. """Splits image identification into base image path, tag/digest
  1064. and it's separator.
  1065. Example:
  1066. >>> parse_repository_tag('user/repo@sha256:digest')
  1067. ('user/repo', 'sha256:digest', '@')
  1068. >>> parse_repository_tag('user/repo:v1')
  1069. ('user/repo', 'v1', ':')
  1070. """
  1071. tag_separator = ":"
  1072. digest_separator = "@"
  1073. if digest_separator in repo_path:
  1074. repo, tag = repo_path.rsplit(digest_separator, 1)
  1075. return repo, tag, digest_separator
  1076. repo, tag = repo_path, ""
  1077. if tag_separator in repo_path:
  1078. repo, tag = repo_path.rsplit(tag_separator, 1)
  1079. if "/" in tag:
  1080. repo, tag = repo_path, ""
  1081. return repo, tag, tag_separator
  1082. # Volumes
  1083. def merge_volume_bindings(volumes, tmpfs, previous_container, mounts):
  1084. """
  1085. Return a list of volume bindings for a container. Container data volumes
  1086. are replaced by those from the previous container.
  1087. Anonymous mounts are updated in place.
  1088. """
  1089. affinity = {}
  1090. volume_bindings = dict(
  1091. build_volume_binding(volume)
  1092. for volume in volumes
  1093. if volume.external
  1094. )
  1095. if previous_container:
  1096. old_volumes, old_mounts = get_container_data_volumes(
  1097. previous_container, volumes, tmpfs, mounts
  1098. )
  1099. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  1100. volume_bindings.update(
  1101. build_volume_binding(volume) for volume in old_volumes
  1102. )
  1103. if old_volumes or old_mounts:
  1104. affinity = {'affinity:container': '=' + previous_container.id}
  1105. return list(volume_bindings.values()), affinity
  1106. def get_container_data_volumes(container, volumes_option, tmpfs_option, mounts_option):
  1107. """
  1108. Find the container data volumes that are in `volumes_option`, and return
  1109. a mapping of volume bindings for those volumes.
  1110. Anonymous volume mounts are updated in place instead.
  1111. """
  1112. volumes = []
  1113. volumes_option = volumes_option or []
  1114. container_mounts = dict(
  1115. (mount['Destination'], mount)
  1116. for mount in container.get('Mounts') or {}
  1117. )
  1118. image_volumes = [
  1119. VolumeSpec.parse(volume)
  1120. for volume in
  1121. container.image_config['ContainerConfig'].get('Volumes') or {}
  1122. ]
  1123. for volume in set(volumes_option + image_volumes):
  1124. # No need to preserve host volumes
  1125. if volume.external:
  1126. continue
  1127. # Attempting to rebind tmpfs volumes breaks: https://github.com/docker/compose/issues/4751
  1128. if volume.internal in convert_tmpfs_mounts(tmpfs_option).keys():
  1129. continue
  1130. mount = container_mounts.get(volume.internal)
  1131. # New volume, doesn't exist in the old container
  1132. if not mount:
  1133. continue
  1134. # Volume was previously a host volume, now it's a container volume
  1135. if not mount.get('Name'):
  1136. continue
  1137. # Copy existing volume from old container
  1138. volume = volume._replace(external=mount['Name'])
  1139. volumes.append(volume)
  1140. updated_mounts = False
  1141. for mount in mounts_option:
  1142. if mount.type != 'volume':
  1143. continue
  1144. ctnr_mount = container_mounts.get(mount.target)
  1145. if not ctnr_mount or not ctnr_mount.get('Name'):
  1146. continue
  1147. mount.source = ctnr_mount['Name']
  1148. updated_mounts = True
  1149. return volumes, updated_mounts
  1150. def warn_on_masked_volume(volumes_option, container_volumes, service):
  1151. container_volumes = dict(
  1152. (volume.internal, volume.external)
  1153. for volume in container_volumes)
  1154. for volume in volumes_option:
  1155. if (
  1156. volume.external and
  1157. volume.internal in container_volumes and
  1158. container_volumes.get(volume.internal) != volume.external
  1159. ):
  1160. log.warn((
  1161. "Service \"{service}\" is using volume \"{volume}\" from the "
  1162. "previous container. Host mapping \"{host_path}\" has no effect. "
  1163. "Remove the existing containers (with `docker-compose rm {service}`) "
  1164. "to use the host volume mapping."
  1165. ).format(
  1166. service=service,
  1167. volume=volume.internal,
  1168. host_path=volume.external))
  1169. def build_volume_binding(volume_spec):
  1170. return volume_spec.internal, volume_spec.repr()
  1171. def build_volume_from(volume_from_spec):
  1172. """
  1173. volume_from can be either a service or a container. We want to return the
  1174. container.id and format it into a string complete with the mode.
  1175. """
  1176. if isinstance(volume_from_spec.source, Service):
  1177. containers = volume_from_spec.source.containers(stopped=True)
  1178. if not containers:
  1179. return "{}:{}".format(
  1180. volume_from_spec.source.create_container().id,
  1181. volume_from_spec.mode)
  1182. container = containers[0]
  1183. return "{}:{}".format(container.id, volume_from_spec.mode)
  1184. elif isinstance(volume_from_spec.source, Container):
  1185. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  1186. def build_mount(mount_spec):
  1187. kwargs = {}
  1188. if mount_spec.options:
  1189. for option, sdk_name in mount_spec.options_map[mount_spec.type].items():
  1190. if option in mount_spec.options:
  1191. kwargs[sdk_name] = mount_spec.options[option]
  1192. return Mount(
  1193. type=mount_spec.type, target=mount_spec.target, source=mount_spec.source,
  1194. read_only=mount_spec.read_only, consistency=mount_spec.consistency, **kwargs
  1195. )
  1196. # Labels
  1197. def build_container_labels(label_options, service_labels, number, config_hash):
  1198. labels = dict(label_options or {})
  1199. labels.update(label.split('=', 1) for label in service_labels)
  1200. labels[LABEL_CONTAINER_NUMBER] = str(number)
  1201. labels[LABEL_VERSION] = __version__
  1202. if config_hash:
  1203. log.debug("Added config hash: %s" % config_hash)
  1204. labels[LABEL_CONFIG_HASH] = config_hash
  1205. return labels
  1206. # Ulimits
  1207. def build_ulimits(ulimit_config):
  1208. if not ulimit_config:
  1209. return None
  1210. ulimits = []
  1211. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  1212. if isinstance(soft_hard_values, six.integer_types):
  1213. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  1214. elif isinstance(soft_hard_values, dict):
  1215. ulimit_dict = {'name': limit_name}
  1216. ulimit_dict.update(soft_hard_values)
  1217. ulimits.append(ulimit_dict)
  1218. return ulimits
  1219. def get_log_config(logging_dict):
  1220. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  1221. log_options = logging_dict.get('options', None) if logging_dict else None
  1222. return LogConfig(
  1223. type=log_driver,
  1224. config=log_options
  1225. )
  1226. # TODO: remove once fix is available in docker-py
  1227. def format_environment(environment):
  1228. def format_env(key, value):
  1229. if value is None:
  1230. return key
  1231. if isinstance(value, six.binary_type):
  1232. value = value.decode('utf-8')
  1233. return '{key}={value}'.format(key=key, value=value)
  1234. return [format_env(*item) for item in environment.items()]
  1235. # Ports
  1236. def formatted_ports(ports):
  1237. result = []
  1238. for port in ports:
  1239. if isinstance(port, ServicePort):
  1240. result.append(port.legacy_repr())
  1241. else:
  1242. result.append(port)
  1243. return result
  1244. def build_container_ports(container_ports, options):
  1245. ports = []
  1246. all_ports = container_ports + options.get('expose', [])
  1247. for port_range in all_ports:
  1248. internal_range, _ = split_port(port_range)
  1249. for port in internal_range:
  1250. port = str(port)
  1251. if '/' in port:
  1252. port = tuple(port.split('/'))
  1253. ports.append(port)
  1254. return ports
  1255. def convert_blkio_config(blkio_config):
  1256. result = {}
  1257. if blkio_config is None:
  1258. return result
  1259. result['weight'] = blkio_config.get('weight')
  1260. for field in [
  1261. "device_read_bps", "device_read_iops", "device_write_bps",
  1262. "device_write_iops", "weight_device",
  1263. ]:
  1264. if field not in blkio_config:
  1265. continue
  1266. arr = []
  1267. for item in blkio_config[field]:
  1268. arr.append(dict([(k.capitalize(), v) for k, v in item.items()]))
  1269. result[field] = arr
  1270. return result