service.py 37 KB

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