service.py 31 KB

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