service.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import re
  5. import sys
  6. from collections import namedtuple
  7. from operator import attrgetter
  8. import enum
  9. import six
  10. from docker.errors import APIError
  11. from docker.utils import LogConfig
  12. from docker.utils.ports import build_port_bindings
  13. from docker.utils.ports import split_port
  14. from . import __version__
  15. from . import progress_stream
  16. from .config import DOCKER_CONFIG_KEYS
  17. from .config import merge_environment
  18. from .config.types import VolumeSpec
  19. from .const import DEFAULT_TIMEOUT
  20. from .const import LABEL_CONFIG_HASH
  21. from .const import LABEL_CONTAINER_NUMBER
  22. from .const import LABEL_ONE_OFF
  23. from .const import LABEL_PROJECT
  24. from .const import LABEL_SERVICE
  25. from .const import LABEL_VERSION
  26. from .container import Container
  27. from .parallel import parallel_execute
  28. from .parallel import parallel_start
  29. from .progress_stream import stream_output
  30. from .progress_stream import StreamOutputError
  31. from .utils import json_hash
  32. log = logging.getLogger(__name__)
  33. DOCKER_START_KEYS = [
  34. 'cap_add',
  35. 'cap_drop',
  36. 'cgroup_parent',
  37. 'cpu_quota',
  38. 'devices',
  39. 'dns',
  40. 'dns_search',
  41. 'env_file',
  42. 'extra_hosts',
  43. 'ipc',
  44. 'read_only',
  45. 'log_driver',
  46. 'log_opt',
  47. 'mem_limit',
  48. 'memswap_limit',
  49. 'oom_score_adj',
  50. 'pid',
  51. 'privileged',
  52. 'restart',
  53. 'security_opt',
  54. 'shm_size',
  55. 'volumes_from',
  56. ]
  57. class BuildError(Exception):
  58. def __init__(self, service, reason):
  59. self.service = service
  60. self.reason = reason
  61. class NeedsBuildError(Exception):
  62. def __init__(self, service):
  63. self.service = service
  64. class NoSuchImageError(Exception):
  65. pass
  66. ServiceName = namedtuple('ServiceName', 'project service number')
  67. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  68. @enum.unique
  69. class ConvergenceStrategy(enum.Enum):
  70. """Enumeration for all possible convergence strategies. Values refer to
  71. when containers should be recreated.
  72. """
  73. changed = 1
  74. always = 2
  75. never = 3
  76. @property
  77. def allows_recreate(self):
  78. return self is not type(self).never
  79. @enum.unique
  80. class ImageType(enum.Enum):
  81. """Enumeration for the types of images known to compose."""
  82. none = 0
  83. local = 1
  84. all = 2
  85. @enum.unique
  86. class BuildAction(enum.Enum):
  87. """Enumeration for the possible build actions."""
  88. none = 0
  89. force = 1
  90. skip = 2
  91. class Service(object):
  92. def __init__(
  93. self,
  94. name,
  95. client=None,
  96. project='default',
  97. use_networking=False,
  98. links=None,
  99. volumes_from=None,
  100. network_mode=None,
  101. networks=None,
  102. **options
  103. ):
  104. self.name = name
  105. self.client = client
  106. self.project = project
  107. self.use_networking = use_networking
  108. self.links = links or []
  109. self.volumes_from = volumes_from or []
  110. self.network_mode = network_mode or NetworkMode(None)
  111. self.networks = networks or {}
  112. self.options = options
  113. def __repr__(self):
  114. return '<Service: {}>'.format(self.name)
  115. def containers(self, stopped=False, one_off=False, filters={}):
  116. filters.update({'label': self.labels(one_off=one_off)})
  117. return list(filter(None, [
  118. Container.from_ps(self.client, container)
  119. for container in self.client.containers(
  120. all=stopped,
  121. filters=filters)]))
  122. def get_container(self, number=1):
  123. """Return a :class:`compose.container.Container` for this service. The
  124. container must be active, and match `number`.
  125. """
  126. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  127. for container in self.client.containers(filters={'label': labels}):
  128. return Container.from_ps(self.client, container)
  129. raise ValueError("No container found for %s_%s" % (self.name, number))
  130. def start(self, **options):
  131. containers = self.containers(stopped=True)
  132. for c in containers:
  133. self.start_container_if_stopped(c, **options)
  134. return containers
  135. def scale(self, desired_num, timeout=DEFAULT_TIMEOUT):
  136. """
  137. Adjusts the number of containers to the specified number and ensures
  138. they are running.
  139. - creates containers until there are at least `desired_num`
  140. - stops containers until there are at most `desired_num` running
  141. - starts containers until there are at least `desired_num` running
  142. - removes all stopped containers
  143. """
  144. if self.custom_container_name and desired_num > 1:
  145. log.warn('The "%s" service is using the custom container name "%s". '
  146. 'Docker requires each container to have a unique name. '
  147. 'Remove the custom name to scale the service.'
  148. % (self.name, self.custom_container_name))
  149. if self.specifies_host_port() and desired_num > 1:
  150. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  151. 'for this service are created on a single host, the port will clash.'
  152. % self.name)
  153. def create_and_start(service, number):
  154. container = service.create_container(number=number, quiet=True)
  155. service.start_container(container)
  156. return container
  157. def stop_and_remove(container):
  158. container.stop(timeout=timeout)
  159. container.remove()
  160. running_containers = self.containers(stopped=False)
  161. num_running = len(running_containers)
  162. if desired_num == num_running:
  163. # do nothing as we already have the desired number
  164. log.info('Desired container number already achieved')
  165. return
  166. if desired_num > num_running:
  167. # we need to start/create until we have desired_num
  168. all_containers = self.containers(stopped=True)
  169. if num_running != len(all_containers):
  170. # we have some stopped containers, let's start them up again
  171. stopped_containers = sorted(
  172. (c for c in all_containers if not c.is_running),
  173. key=attrgetter('number'))
  174. num_stopped = len(stopped_containers)
  175. if num_stopped + num_running > desired_num:
  176. num_to_start = desired_num - num_running
  177. containers_to_start = stopped_containers[:num_to_start]
  178. else:
  179. containers_to_start = stopped_containers
  180. parallel_start(containers_to_start, {})
  181. num_running += len(containers_to_start)
  182. num_to_create = desired_num - num_running
  183. next_number = self._next_container_number()
  184. container_numbers = [
  185. number for number in range(
  186. next_number, next_number + num_to_create
  187. )
  188. ]
  189. parallel_execute(
  190. container_numbers,
  191. lambda n: create_and_start(service=self, number=n),
  192. lambda n: self.get_container_name(n),
  193. "Creating and starting"
  194. )
  195. if desired_num < num_running:
  196. num_to_stop = num_running - desired_num
  197. sorted_running_containers = sorted(
  198. running_containers,
  199. key=attrgetter('number'))
  200. parallel_execute(
  201. sorted_running_containers[-num_to_stop:],
  202. stop_and_remove,
  203. lambda c: c.name,
  204. "Stopping and removing",
  205. )
  206. def create_container(self,
  207. one_off=False,
  208. previous_container=None,
  209. number=None,
  210. quiet=False,
  211. **override_options):
  212. """
  213. Create a container for this service. If the image doesn't exist, attempt to pull
  214. it.
  215. """
  216. # This is only necessary for `scale` and `volumes_from`
  217. # auto-creating containers to satisfy the dependency.
  218. self.ensure_image_exists()
  219. container_options = self._get_container_create_options(
  220. override_options,
  221. number or self._next_container_number(one_off=one_off),
  222. one_off=one_off,
  223. previous_container=previous_container,
  224. )
  225. if 'name' in container_options and not quiet:
  226. log.info("Creating %s" % container_options['name'])
  227. return Container.create(self.client, **container_options)
  228. def ensure_image_exists(self, do_build=BuildAction.none):
  229. if self.can_be_built() and do_build == BuildAction.force:
  230. self.build()
  231. return
  232. try:
  233. self.image()
  234. return
  235. except NoSuchImageError:
  236. pass
  237. if not self.can_be_built():
  238. self.pull()
  239. return
  240. if do_build == BuildAction.skip:
  241. raise NeedsBuildError(self)
  242. self.build()
  243. log.warn(
  244. "Image for service {} was built because it did not already exist. To "
  245. "rebuild this image you must use `docker-compose build` or "
  246. "`docker-compose up --build`.".format(self.name))
  247. def image(self):
  248. try:
  249. return self.client.inspect_image(self.image_name)
  250. except APIError as e:
  251. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  252. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  253. else:
  254. raise
  255. @property
  256. def image_name(self):
  257. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  258. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  259. containers = self.containers(stopped=True)
  260. if not containers:
  261. return ConvergencePlan('create', [])
  262. if strategy is ConvergenceStrategy.never:
  263. return ConvergencePlan('start', containers)
  264. if (
  265. strategy is ConvergenceStrategy.always or
  266. self._containers_have_diverged(containers)
  267. ):
  268. return ConvergencePlan('recreate', containers)
  269. stopped = [c for c in containers if not c.is_running]
  270. if stopped:
  271. return ConvergencePlan('start', stopped)
  272. return ConvergencePlan('noop', containers)
  273. def _containers_have_diverged(self, containers):
  274. config_hash = None
  275. try:
  276. config_hash = self.config_hash
  277. except NoSuchImageError as e:
  278. log.debug(
  279. 'Service %s has diverged: %s',
  280. self.name, six.text_type(e),
  281. )
  282. return True
  283. has_diverged = False
  284. for c in containers:
  285. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  286. if container_config_hash != config_hash:
  287. log.debug(
  288. '%s has diverged: %s != %s',
  289. c.name, container_config_hash, config_hash,
  290. )
  291. has_diverged = True
  292. return has_diverged
  293. def execute_convergence_plan(self,
  294. plan,
  295. timeout=DEFAULT_TIMEOUT,
  296. detached=False,
  297. start=True):
  298. (action, containers) = plan
  299. should_attach_logs = not detached
  300. if action == 'create':
  301. container = self.create_container()
  302. if should_attach_logs:
  303. container.attach_log_stream()
  304. if start:
  305. self.start_container(container)
  306. return [container]
  307. elif action == 'recreate':
  308. return [
  309. self.recreate_container(
  310. container,
  311. timeout=timeout,
  312. attach_logs=should_attach_logs,
  313. start_new_container=start
  314. )
  315. for container in containers
  316. ]
  317. elif action == 'start':
  318. if start:
  319. for container in containers:
  320. self.start_container_if_stopped(container, attach_logs=should_attach_logs)
  321. return containers
  322. elif action == 'noop':
  323. for c in containers:
  324. log.info("%s is up-to-date" % c.name)
  325. return containers
  326. else:
  327. raise Exception("Invalid action: {}".format(action))
  328. def recreate_container(
  329. self,
  330. container,
  331. timeout=DEFAULT_TIMEOUT,
  332. attach_logs=False,
  333. start_new_container=True):
  334. """Recreate a container.
  335. The original container is renamed to a temporary name so that data
  336. volumes can be copied to the new container, before the original
  337. container is removed.
  338. """
  339. log.info("Recreating %s" % container.name)
  340. container.stop(timeout=timeout)
  341. container.rename_to_tmp_name()
  342. new_container = self.create_container(
  343. previous_container=container,
  344. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  345. quiet=True,
  346. )
  347. if attach_logs:
  348. new_container.attach_log_stream()
  349. if start_new_container:
  350. self.start_container(new_container)
  351. container.remove()
  352. return new_container
  353. def start_container_if_stopped(self, container, attach_logs=False, quiet=False):
  354. if not container.is_running:
  355. if not quiet:
  356. log.info("Starting %s" % container.name)
  357. if attach_logs:
  358. container.attach_log_stream()
  359. return self.start_container(container)
  360. def start_container(self, container):
  361. self.connect_container_to_networks(container)
  362. container.start()
  363. return container
  364. def connect_container_to_networks(self, container):
  365. connected_networks = container.get('NetworkSettings.Networks')
  366. for network, netdefs in self.networks.items():
  367. if network in connected_networks:
  368. if short_id_alias_exists(container, network):
  369. continue
  370. self.client.disconnect_container_from_network(
  371. container.id,
  372. network)
  373. self.client.connect_container_to_network(
  374. container.id, network,
  375. aliases=self._get_aliases(netdefs, container),
  376. ipv4_address=netdefs.get('ipv4_address', None),
  377. ipv6_address=netdefs.get('ipv6_address', None),
  378. links=self._get_links(False))
  379. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  380. for c in self.duplicate_containers():
  381. log.info('Removing %s' % c.name)
  382. c.stop(timeout=timeout)
  383. c.remove()
  384. def duplicate_containers(self):
  385. containers = sorted(
  386. self.containers(stopped=True),
  387. key=lambda c: c.get('Created'),
  388. )
  389. numbers = set()
  390. for c in containers:
  391. if c.number in numbers:
  392. yield c
  393. else:
  394. numbers.add(c.number)
  395. @property
  396. def config_hash(self):
  397. return json_hash(self.config_dict())
  398. def config_dict(self):
  399. return {
  400. 'options': self.options,
  401. 'image_id': self.image()['Id'],
  402. 'links': self.get_link_names(),
  403. 'net': self.network_mode.id,
  404. 'networks': self.networks,
  405. 'volumes_from': [
  406. (v.source.name, v.mode)
  407. for v in self.volumes_from if isinstance(v.source, Service)
  408. ],
  409. }
  410. def get_dependency_names(self):
  411. net_name = self.network_mode.service_name
  412. return (self.get_linked_service_names() +
  413. self.get_volumes_from_names() +
  414. ([net_name] if net_name else []) +
  415. self.options.get('depends_on', []))
  416. def get_linked_service_names(self):
  417. return [service.name for (service, _) in self.links]
  418. def get_link_names(self):
  419. return [(service.name, alias) for service, alias in self.links]
  420. def get_volumes_from_names(self):
  421. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  422. # TODO: this would benefit from github.com/docker/docker/pull/14699
  423. # to remove the need to inspect every container
  424. def _next_container_number(self, one_off=False):
  425. containers = filter(None, [
  426. Container.from_ps(self.client, container)
  427. for container in self.client.containers(
  428. all=True,
  429. filters={'label': self.labels(one_off=one_off)})
  430. ])
  431. numbers = [c.number for c in containers]
  432. return 1 if not numbers else max(numbers) + 1
  433. def _get_aliases(self, network, container=None):
  434. if container and container.labels.get(LABEL_ONE_OFF) == "True":
  435. return []
  436. return list(
  437. {self.name} |
  438. ({container.short_id} if container else set()) |
  439. set(network.get('aliases', ()))
  440. )
  441. def build_default_networking_config(self):
  442. if not self.networks:
  443. return {}
  444. network = self.networks[self.network_mode.id]
  445. endpoint = {
  446. 'Aliases': self._get_aliases(network),
  447. 'IPAMConfig': {},
  448. }
  449. if network.get('ipv4_address'):
  450. endpoint['IPAMConfig']['IPv4Address'] = network.get('ipv4_address')
  451. if network.get('ipv6_address'):
  452. endpoint['IPAMConfig']['IPv6Address'] = network.get('ipv6_address')
  453. return {"EndpointsConfig": {self.network_mode.id: endpoint}}
  454. def _get_links(self, link_to_self):
  455. links = {}
  456. for service, link_name in self.links:
  457. for container in service.containers():
  458. links[link_name or service.name] = container.name
  459. links[container.name] = container.name
  460. links[container.name_without_project] = container.name
  461. if link_to_self:
  462. for container in self.containers():
  463. links[self.name] = container.name
  464. links[container.name] = container.name
  465. links[container.name_without_project] = container.name
  466. for external_link in self.options.get('external_links') or []:
  467. if ':' not in external_link:
  468. link_name = external_link
  469. else:
  470. external_link, link_name = external_link.split(':')
  471. links[link_name] = external_link
  472. return [
  473. (alias, container_name)
  474. for (container_name, alias) in links.items()
  475. ]
  476. def _get_volumes_from(self):
  477. return [build_volume_from(spec) for spec in self.volumes_from]
  478. def _get_container_create_options(
  479. self,
  480. override_options,
  481. number,
  482. one_off=False,
  483. previous_container=None):
  484. add_config_hash = (not one_off and not override_options)
  485. container_options = dict(
  486. (k, self.options[k])
  487. for k in DOCKER_CONFIG_KEYS if k in self.options)
  488. container_options.update(override_options)
  489. if not container_options.get('name'):
  490. container_options['name'] = self.get_container_name(number, one_off)
  491. container_options.setdefault('detach', True)
  492. # If a qualified hostname was given, split it into an
  493. # unqualified hostname and a domainname unless domainname
  494. # was also given explicitly. This matches the behavior of
  495. # the official Docker CLI in that scenario.
  496. if ('hostname' in container_options and
  497. 'domainname' not in container_options and
  498. '.' in container_options['hostname']):
  499. parts = container_options['hostname'].partition('.')
  500. container_options['hostname'] = parts[0]
  501. container_options['domainname'] = parts[2]
  502. if 'ports' in container_options or 'expose' in self.options:
  503. container_options['ports'] = build_container_ports(
  504. container_options,
  505. self.options)
  506. container_options['environment'] = merge_environment(
  507. self.options.get('environment'),
  508. override_options.get('environment'))
  509. binds, affinity = merge_volume_bindings(
  510. container_options.get('volumes') or [],
  511. previous_container)
  512. override_options['binds'] = binds
  513. container_options['environment'].update(affinity)
  514. if 'volumes' in container_options:
  515. container_options['volumes'] = dict(
  516. (v.internal, {}) for v in container_options['volumes'])
  517. container_options['image'] = self.image_name
  518. container_options['labels'] = build_container_labels(
  519. container_options.get('labels', {}),
  520. self.labels(one_off=one_off),
  521. number,
  522. self.config_hash if add_config_hash else None)
  523. # Delete options which are only used when starting
  524. for key in DOCKER_START_KEYS:
  525. container_options.pop(key, None)
  526. container_options['host_config'] = self._get_container_host_config(
  527. override_options,
  528. one_off=one_off)
  529. networking_config = self.build_default_networking_config()
  530. if networking_config:
  531. container_options['networking_config'] = networking_config
  532. container_options['environment'] = format_environment(
  533. container_options['environment'])
  534. return container_options
  535. def _get_container_host_config(self, override_options, one_off=False):
  536. options = dict(self.options, **override_options)
  537. logging_dict = options.get('logging', None)
  538. log_config = get_log_config(logging_dict)
  539. return self.client.create_host_config(
  540. links=self._get_links(link_to_self=one_off),
  541. port_bindings=build_port_bindings(options.get('ports') or []),
  542. binds=options.get('binds'),
  543. volumes_from=self._get_volumes_from(),
  544. privileged=options.get('privileged', False),
  545. network_mode=self.network_mode.mode,
  546. devices=options.get('devices'),
  547. dns=options.get('dns'),
  548. dns_search=options.get('dns_search'),
  549. restart_policy=options.get('restart'),
  550. cap_add=options.get('cap_add'),
  551. cap_drop=options.get('cap_drop'),
  552. mem_limit=options.get('mem_limit'),
  553. memswap_limit=options.get('memswap_limit'),
  554. ulimits=build_ulimits(options.get('ulimits')),
  555. log_config=log_config,
  556. extra_hosts=options.get('extra_hosts'),
  557. read_only=options.get('read_only'),
  558. pid_mode=options.get('pid'),
  559. security_opt=options.get('security_opt'),
  560. ipc_mode=options.get('ipc'),
  561. cgroup_parent=options.get('cgroup_parent'),
  562. cpu_quota=options.get('cpu_quota'),
  563. shm_size=options.get('shm_size'),
  564. tmpfs=options.get('tmpfs'),
  565. oom_score_adj=options.get('oom_score_adj')
  566. )
  567. def build(self, no_cache=False, pull=False, force_rm=False):
  568. log.info('Building %s' % self.name)
  569. build_opts = self.options.get('build', {})
  570. path = build_opts.get('context')
  571. # python2 os.path() doesn't support unicode, so we need to encode it to
  572. # a byte string
  573. if not six.PY3:
  574. path = path.encode('utf8')
  575. build_output = self.client.build(
  576. path=path,
  577. tag=self.image_name,
  578. stream=True,
  579. rm=True,
  580. forcerm=force_rm,
  581. pull=pull,
  582. nocache=no_cache,
  583. dockerfile=build_opts.get('dockerfile', None),
  584. buildargs=build_opts.get('args', None),
  585. )
  586. try:
  587. all_events = stream_output(build_output, sys.stdout)
  588. except StreamOutputError as e:
  589. raise BuildError(self, six.text_type(e))
  590. # Ensure the HTTP connection is not reused for another
  591. # streaming command, as the Docker daemon can sometimes
  592. # complain about it
  593. self.client.close()
  594. image_id = None
  595. for event in all_events:
  596. if 'stream' in event:
  597. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  598. if match:
  599. image_id = match.group(1)
  600. if image_id is None:
  601. raise BuildError(self, event if all_events else 'Unknown')
  602. return image_id
  603. def can_be_built(self):
  604. return 'build' in self.options
  605. def labels(self, one_off=False):
  606. return [
  607. '{0}={1}'.format(LABEL_PROJECT, self.project),
  608. '{0}={1}'.format(LABEL_SERVICE, self.name),
  609. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  610. ]
  611. @property
  612. def custom_container_name(self):
  613. return self.options.get('container_name')
  614. def get_container_name(self, number, one_off=False):
  615. if self.custom_container_name and not one_off:
  616. return self.custom_container_name
  617. return build_container_name(self.project, self.name, number, one_off)
  618. def remove_image(self, image_type):
  619. if not image_type or image_type == ImageType.none:
  620. return False
  621. if image_type == ImageType.local and self.options.get('image'):
  622. return False
  623. log.info("Removing image %s", self.image_name)
  624. try:
  625. self.client.remove_image(self.image_name)
  626. return True
  627. except APIError as e:
  628. log.error("Failed to remove image for service %s: %s", self.name, e)
  629. return False
  630. def specifies_host_port(self):
  631. def has_host_port(binding):
  632. _, external_bindings = split_port(binding)
  633. # there are no external bindings
  634. if external_bindings is None:
  635. return False
  636. # we only need to check the first binding from the range
  637. external_binding = external_bindings[0]
  638. # non-tuple binding means there is a host port specified
  639. if not isinstance(external_binding, tuple):
  640. return True
  641. # extract actual host port from tuple of (host_ip, host_port)
  642. _, host_port = external_binding
  643. if host_port is not None:
  644. return True
  645. return False
  646. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  647. def pull(self, ignore_pull_failures=False):
  648. if 'image' not in self.options:
  649. return
  650. repo, tag, separator = parse_repository_tag(self.options['image'])
  651. tag = tag or 'latest'
  652. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  653. output = self.client.pull(repo, tag=tag, stream=True)
  654. try:
  655. return progress_stream.get_digest_from_pull(
  656. stream_output(output, sys.stdout))
  657. except StreamOutputError as e:
  658. if not ignore_pull_failures:
  659. raise
  660. else:
  661. log.error(six.text_type(e))
  662. def push(self, ignore_push_failures=False):
  663. if 'image' not in self.options or 'build' not in self.options:
  664. return
  665. repo, tag, separator = parse_repository_tag(self.options['image'])
  666. tag = tag or 'latest'
  667. log.info('Pushing %s (%s%s%s)...' % (self.name, repo, separator, tag))
  668. output = self.client.push(repo, tag=tag, stream=True)
  669. try:
  670. return progress_stream.get_digest_from_push(
  671. stream_output(output, sys.stdout))
  672. except StreamOutputError as e:
  673. if not ignore_push_failures:
  674. raise
  675. else:
  676. log.error(six.text_type(e))
  677. def short_id_alias_exists(container, network):
  678. aliases = container.get(
  679. 'NetworkSettings.Networks.{net}.Aliases'.format(net=network)) or ()
  680. return container.short_id in aliases
  681. class NetworkMode(object):
  682. """A `standard` network mode (ex: host, bridge)"""
  683. service_name = None
  684. def __init__(self, network_mode):
  685. self.network_mode = network_mode
  686. @property
  687. def id(self):
  688. return self.network_mode
  689. mode = id
  690. class ContainerNetworkMode(object):
  691. """A network mode that uses a container's network stack."""
  692. service_name = None
  693. def __init__(self, container):
  694. self.container = container
  695. @property
  696. def id(self):
  697. return self.container.id
  698. @property
  699. def mode(self):
  700. return 'container:' + self.container.id
  701. class ServiceNetworkMode(object):
  702. """A network mode that uses a service's network stack."""
  703. def __init__(self, service):
  704. self.service = service
  705. @property
  706. def id(self):
  707. return self.service.name
  708. service_name = id
  709. @property
  710. def mode(self):
  711. containers = self.service.containers()
  712. if containers:
  713. return 'container:' + containers[0].id
  714. log.warn("Service %s is trying to use reuse the network stack "
  715. "of another service that is not running." % (self.id))
  716. return None
  717. # Names
  718. def build_container_name(project, service, number, one_off=False):
  719. bits = [project, service]
  720. if one_off:
  721. bits.append('run')
  722. return '_'.join(bits + [str(number)])
  723. # Images
  724. def parse_repository_tag(repo_path):
  725. """Splits image identification into base image path, tag/digest
  726. and it's separator.
  727. Example:
  728. >>> parse_repository_tag('user/repo@sha256:digest')
  729. ('user/repo', 'sha256:digest', '@')
  730. >>> parse_repository_tag('user/repo:v1')
  731. ('user/repo', 'v1', ':')
  732. """
  733. tag_separator = ":"
  734. digest_separator = "@"
  735. if digest_separator in repo_path:
  736. repo, tag = repo_path.rsplit(digest_separator, 1)
  737. return repo, tag, digest_separator
  738. repo, tag = repo_path, ""
  739. if tag_separator in repo_path:
  740. repo, tag = repo_path.rsplit(tag_separator, 1)
  741. if "/" in tag:
  742. repo, tag = repo_path, ""
  743. return repo, tag, tag_separator
  744. # Volumes
  745. def merge_volume_bindings(volumes, previous_container):
  746. """Return a list of volume bindings for a container. Container data volumes
  747. are replaced by those from the previous container.
  748. """
  749. affinity = {}
  750. volume_bindings = dict(
  751. build_volume_binding(volume)
  752. for volume in volumes
  753. if volume.external)
  754. if previous_container:
  755. old_volumes = get_container_data_volumes(previous_container, volumes)
  756. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  757. volume_bindings.update(
  758. build_volume_binding(volume) for volume in old_volumes)
  759. if old_volumes:
  760. affinity = {'affinity:container': '=' + previous_container.id}
  761. return list(volume_bindings.values()), affinity
  762. def get_container_data_volumes(container, volumes_option):
  763. """Find the container data volumes that are in `volumes_option`, and return
  764. a mapping of volume bindings for those volumes.
  765. """
  766. volumes = []
  767. volumes_option = volumes_option or []
  768. container_mounts = dict(
  769. (mount['Destination'], mount)
  770. for mount in container.get('Mounts') or {}
  771. )
  772. image_volumes = [
  773. VolumeSpec.parse(volume)
  774. for volume in
  775. container.image_config['ContainerConfig'].get('Volumes') or {}
  776. ]
  777. for volume in set(volumes_option + image_volumes):
  778. # No need to preserve host volumes
  779. if volume.external:
  780. continue
  781. mount = container_mounts.get(volume.internal)
  782. # New volume, doesn't exist in the old container
  783. if not mount:
  784. continue
  785. # Volume was previously a host volume, now it's a container volume
  786. if not mount.get('Name'):
  787. continue
  788. # Copy existing volume from old container
  789. volume = volume._replace(external=mount['Name'])
  790. volumes.append(volume)
  791. return volumes
  792. def warn_on_masked_volume(volumes_option, container_volumes, service):
  793. container_volumes = dict(
  794. (volume.internal, volume.external)
  795. for volume in container_volumes)
  796. for volume in volumes_option:
  797. if (
  798. volume.external and
  799. volume.internal in container_volumes and
  800. container_volumes.get(volume.internal) != volume.external
  801. ):
  802. log.warn((
  803. "Service \"{service}\" is using volume \"{volume}\" from the "
  804. "previous container. Host mapping \"{host_path}\" has no effect. "
  805. "Remove the existing containers (with `docker-compose rm {service}`) "
  806. "to use the host volume mapping."
  807. ).format(
  808. service=service,
  809. volume=volume.internal,
  810. host_path=volume.external))
  811. def build_volume_binding(volume_spec):
  812. return volume_spec.internal, volume_spec.repr()
  813. def build_volume_from(volume_from_spec):
  814. """
  815. volume_from can be either a service or a container. We want to return the
  816. container.id and format it into a string complete with the mode.
  817. """
  818. if isinstance(volume_from_spec.source, Service):
  819. containers = volume_from_spec.source.containers(stopped=True)
  820. if not containers:
  821. return "{}:{}".format(
  822. volume_from_spec.source.create_container().id,
  823. volume_from_spec.mode)
  824. container = containers[0]
  825. return "{}:{}".format(container.id, volume_from_spec.mode)
  826. elif isinstance(volume_from_spec.source, Container):
  827. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  828. # Labels
  829. def build_container_labels(label_options, service_labels, number, config_hash):
  830. labels = dict(label_options or {})
  831. labels.update(label.split('=', 1) for label in service_labels)
  832. labels[LABEL_CONTAINER_NUMBER] = str(number)
  833. labels[LABEL_VERSION] = __version__
  834. if config_hash:
  835. log.debug("Added config hash: %s" % config_hash)
  836. labels[LABEL_CONFIG_HASH] = config_hash
  837. return labels
  838. # Ulimits
  839. def build_ulimits(ulimit_config):
  840. if not ulimit_config:
  841. return None
  842. ulimits = []
  843. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  844. if isinstance(soft_hard_values, six.integer_types):
  845. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  846. elif isinstance(soft_hard_values, dict):
  847. ulimit_dict = {'name': limit_name}
  848. ulimit_dict.update(soft_hard_values)
  849. ulimits.append(ulimit_dict)
  850. return ulimits
  851. def get_log_config(logging_dict):
  852. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  853. log_options = logging_dict.get('options', None) if logging_dict else None
  854. return LogConfig(
  855. type=log_driver,
  856. config=log_options
  857. )
  858. # TODO: remove once fix is available in docker-py
  859. def format_environment(environment):
  860. def format_env(key, value):
  861. if value is None:
  862. return key
  863. return '{key}={value}'.format(key=key, value=value)
  864. return [format_env(*item) for item in environment.items()]
  865. # Ports
  866. def build_container_ports(container_options, options):
  867. ports = []
  868. all_ports = container_options.get('ports', []) + options.get('expose', [])
  869. for port_range in all_ports:
  870. internal_range, _ = split_port(port_range)
  871. for port in internal_range:
  872. port = str(port)
  873. if '/' in port:
  874. port = tuple(port.split('/'))
  875. ports.append(port)
  876. return ports