service.py 32 KB

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