service.py 36 KB

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