service.py 34 KB

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