1
0

service.py 51 KB

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