service.py 32 KB

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