service.py 51 KB

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