service.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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. 'cpu_quota',
  37. 'devices',
  38. 'dns',
  39. 'dns_search',
  40. 'env_file',
  41. 'extra_hosts',
  42. 'ipc',
  43. 'read_only',
  44. 'log_driver',
  45. 'log_opt',
  46. 'mem_limit',
  47. 'memswap_limit',
  48. 'pid',
  49. 'privileged',
  50. 'restart',
  51. 'security_opt',
  52. 'shm_size',
  53. 'volumes_from',
  54. ]
  55. class BuildError(Exception):
  56. def __init__(self, service, reason):
  57. self.service = service
  58. self.reason = reason
  59. class NeedsBuildError(Exception):
  60. def __init__(self, service):
  61. self.service = service
  62. class NoSuchImageError(Exception):
  63. pass
  64. ServiceName = namedtuple('ServiceName', 'project service number')
  65. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  66. @enum.unique
  67. class ConvergenceStrategy(enum.Enum):
  68. """Enumeration for all possible convergence strategies. Values refer to
  69. when containers should be recreated.
  70. """
  71. changed = 1
  72. always = 2
  73. never = 3
  74. @property
  75. def allows_recreate(self):
  76. return self is not type(self).never
  77. @enum.unique
  78. class ImageType(enum.Enum):
  79. """Enumeration for the types of images known to compose."""
  80. none = 0
  81. local = 1
  82. all = 2
  83. class Service(object):
  84. def __init__(
  85. self,
  86. name,
  87. client=None,
  88. project='default',
  89. use_networking=False,
  90. links=None,
  91. volumes_from=None,
  92. network_mode=None,
  93. networks=None,
  94. **options
  95. ):
  96. self.name = name
  97. self.client = client
  98. self.project = project
  99. self.use_networking = use_networking
  100. self.links = links or []
  101. self.volumes_from = volumes_from or []
  102. self.network_mode = network_mode or NetworkMode(None)
  103. self.networks = networks or {}
  104. self.options = options
  105. def containers(self, stopped=False, one_off=False, filters={}):
  106. filters.update({'label': self.labels(one_off=one_off)})
  107. return list(filter(None, [
  108. Container.from_ps(self.client, container)
  109. for container in self.client.containers(
  110. all=stopped,
  111. filters=filters)]))
  112. def get_container(self, number=1):
  113. """Return a :class:`compose.container.Container` for this service. The
  114. container must be active, and match `number`.
  115. """
  116. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  117. for container in self.client.containers(filters={'label': labels}):
  118. return Container.from_ps(self.client, container)
  119. raise ValueError("No container found for %s_%s" % (self.name, number))
  120. def start(self, **options):
  121. containers = self.containers(stopped=True)
  122. for c in containers:
  123. self.start_container_if_stopped(c, **options)
  124. return containers
  125. def scale(self, desired_num, timeout=DEFAULT_TIMEOUT):
  126. """
  127. Adjusts the number of containers to the specified number and ensures
  128. they are running.
  129. - creates containers until there are at least `desired_num`
  130. - stops containers until there are at most `desired_num` running
  131. - starts containers until there are at least `desired_num` running
  132. - removes all stopped containers
  133. """
  134. if self.custom_container_name and desired_num > 1:
  135. log.warn('The "%s" service is using the custom container name "%s". '
  136. 'Docker requires each container to have a unique name. '
  137. 'Remove the custom name to scale the service.'
  138. % (self.name, self.custom_container_name))
  139. if self.specifies_host_port():
  140. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  141. 'for this service are created on a single host, the port will clash.'
  142. % self.name)
  143. def create_and_start(service, number):
  144. container = service.create_container(number=number, quiet=True)
  145. service.start_container(container)
  146. return container
  147. def stop_and_remove(container):
  148. container.stop(timeout=timeout)
  149. container.remove()
  150. running_containers = self.containers(stopped=False)
  151. num_running = len(running_containers)
  152. if desired_num == num_running:
  153. # do nothing as we already have the desired number
  154. log.info('Desired container number already achieved')
  155. return
  156. if desired_num > num_running:
  157. # we need to start/create until we have desired_num
  158. all_containers = self.containers(stopped=True)
  159. if num_running != len(all_containers):
  160. # we have some stopped containers, let's start them up again
  161. stopped_containers = sorted([c for c in all_containers if not c.is_running], key=attrgetter('number'))
  162. num_stopped = len(stopped_containers)
  163. if num_stopped + num_running > desired_num:
  164. num_to_start = desired_num - num_running
  165. containers_to_start = stopped_containers[:num_to_start]
  166. else:
  167. containers_to_start = stopped_containers
  168. parallel_start(containers_to_start, {})
  169. num_running += len(containers_to_start)
  170. num_to_create = desired_num - num_running
  171. next_number = self._next_container_number()
  172. container_numbers = [
  173. number for number in range(
  174. next_number, next_number + num_to_create
  175. )
  176. ]
  177. parallel_execute(
  178. container_numbers,
  179. lambda n: create_and_start(service=self, number=n),
  180. lambda n: n,
  181. "Creating and starting"
  182. )
  183. if desired_num < num_running:
  184. num_to_stop = num_running - desired_num
  185. sorted_running_containers = sorted(
  186. running_containers,
  187. key=attrgetter('number'))
  188. parallel_execute(
  189. sorted_running_containers[-num_to_stop:],
  190. stop_and_remove,
  191. lambda c: c.name,
  192. "Stopping and removing",
  193. )
  194. def create_container(self,
  195. one_off=False,
  196. do_build=True,
  197. previous_container=None,
  198. number=None,
  199. quiet=False,
  200. **override_options):
  201. """
  202. Create a container for this service. If the image doesn't exist, attempt to pull
  203. it.
  204. """
  205. self.ensure_image_exists(do_build=do_build)
  206. container_options = self._get_container_create_options(
  207. override_options,
  208. number or self._next_container_number(one_off=one_off),
  209. one_off=one_off,
  210. previous_container=previous_container,
  211. )
  212. if 'name' in container_options and not quiet:
  213. log.info("Creating %s" % container_options['name'])
  214. return Container.create(self.client, **container_options)
  215. def ensure_image_exists(self, do_build=True):
  216. try:
  217. self.image()
  218. return
  219. except NoSuchImageError:
  220. pass
  221. if self.can_be_built():
  222. if do_build:
  223. self.build()
  224. else:
  225. raise NeedsBuildError(self)
  226. else:
  227. self.pull()
  228. def image(self):
  229. try:
  230. return self.client.inspect_image(self.image_name)
  231. except APIError as e:
  232. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  233. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  234. else:
  235. raise
  236. @property
  237. def image_name(self):
  238. return self.options.get('image', '{s.project}_{s.name}'.format(s=self))
  239. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  240. containers = self.containers(stopped=True)
  241. if not containers:
  242. return ConvergencePlan('create', [])
  243. if strategy is ConvergenceStrategy.never:
  244. return ConvergencePlan('start', containers)
  245. if (
  246. strategy is ConvergenceStrategy.always or
  247. self._containers_have_diverged(containers)
  248. ):
  249. return ConvergencePlan('recreate', containers)
  250. stopped = [c for c in containers if not c.is_running]
  251. if stopped:
  252. return ConvergencePlan('start', stopped)
  253. return ConvergencePlan('noop', containers)
  254. def _containers_have_diverged(self, containers):
  255. config_hash = None
  256. try:
  257. config_hash = self.config_hash
  258. except NoSuchImageError as e:
  259. log.debug(
  260. 'Service %s has diverged: %s',
  261. self.name, six.text_type(e),
  262. )
  263. return True
  264. has_diverged = False
  265. for c in containers:
  266. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  267. if container_config_hash != config_hash:
  268. log.debug(
  269. '%s has diverged: %s != %s',
  270. c.name, container_config_hash, config_hash,
  271. )
  272. has_diverged = True
  273. return has_diverged
  274. def execute_convergence_plan(self,
  275. plan,
  276. do_build=True,
  277. timeout=DEFAULT_TIMEOUT,
  278. detached=False,
  279. start=True):
  280. (action, containers) = plan
  281. should_attach_logs = not detached
  282. if action == 'create':
  283. container = self.create_container(do_build=do_build)
  284. if should_attach_logs:
  285. container.attach_log_stream()
  286. if start:
  287. self.start_container(container)
  288. return [container]
  289. elif action == 'recreate':
  290. return [
  291. self.recreate_container(
  292. container,
  293. do_build=do_build,
  294. timeout=timeout,
  295. attach_logs=should_attach_logs,
  296. start_new_container=start
  297. )
  298. for container in containers
  299. ]
  300. elif action == 'start':
  301. if start:
  302. for container in containers:
  303. self.start_container_if_stopped(container, attach_logs=should_attach_logs)
  304. return containers
  305. elif action == 'noop':
  306. for c in containers:
  307. log.info("%s is up-to-date" % c.name)
  308. return containers
  309. else:
  310. raise Exception("Invalid action: {}".format(action))
  311. def recreate_container(
  312. self,
  313. container,
  314. do_build=False,
  315. timeout=DEFAULT_TIMEOUT,
  316. attach_logs=False,
  317. start_new_container=True):
  318. """Recreate a container.
  319. The original container is renamed to a temporary name so that data
  320. volumes can be copied to the new container, before the original
  321. container is removed.
  322. """
  323. log.info("Recreating %s" % container.name)
  324. container.stop(timeout=timeout)
  325. container.rename_to_tmp_name()
  326. new_container = self.create_container(
  327. do_build=do_build,
  328. previous_container=container,
  329. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  330. quiet=True,
  331. )
  332. if attach_logs:
  333. new_container.attach_log_stream()
  334. if start_new_container:
  335. self.start_container(new_container)
  336. container.remove()
  337. return new_container
  338. def start_container_if_stopped(self, container, attach_logs=False):
  339. if not container.is_running:
  340. log.info("Starting %s" % container.name)
  341. if attach_logs:
  342. container.attach_log_stream()
  343. return self.start_container(container)
  344. def start_container(self, container):
  345. self.connect_container_to_networks(container)
  346. container.start()
  347. return container
  348. def connect_container_to_networks(self, container):
  349. connected_networks = container.get('NetworkSettings.Networks')
  350. for network, aliases in self.networks.items():
  351. if network in connected_networks:
  352. self.client.disconnect_container_from_network(
  353. container.id, network)
  354. self.client.connect_container_to_network(
  355. container.id, network,
  356. aliases=list(self._get_aliases(container).union(aliases)),
  357. links=self._get_links(False),
  358. )
  359. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  360. for c in self.duplicate_containers():
  361. log.info('Removing %s' % c.name)
  362. c.stop(timeout=timeout)
  363. c.remove()
  364. def duplicate_containers(self):
  365. containers = sorted(
  366. self.containers(stopped=True),
  367. key=lambda c: c.get('Created'),
  368. )
  369. numbers = set()
  370. for c in containers:
  371. if c.number in numbers:
  372. yield c
  373. else:
  374. numbers.add(c.number)
  375. @property
  376. def config_hash(self):
  377. return json_hash(self.config_dict())
  378. def config_dict(self):
  379. return {
  380. 'options': self.options,
  381. 'image_id': self.image()['Id'],
  382. 'links': self.get_link_names(),
  383. 'net': self.network_mode.id,
  384. 'networks': list(self.networks.keys()),
  385. 'volumes_from': [
  386. (v.source.name, v.mode)
  387. for v in self.volumes_from if isinstance(v.source, Service)
  388. ],
  389. }
  390. def get_dependency_names(self):
  391. net_name = self.network_mode.service_name
  392. return (self.get_linked_service_names() +
  393. self.get_volumes_from_names() +
  394. ([net_name] if net_name else []) +
  395. self.options.get('depends_on', []))
  396. def get_linked_service_names(self):
  397. return [service.name for (service, _) in self.links]
  398. def get_link_names(self):
  399. return [(service.name, alias) for service, alias in self.links]
  400. def get_volumes_from_names(self):
  401. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  402. # TODO: this would benefit from github.com/docker/docker/pull/14699
  403. # to remove the need to inspect every container
  404. def _next_container_number(self, one_off=False):
  405. containers = filter(None, [
  406. Container.from_ps(self.client, container)
  407. for container in self.client.containers(
  408. all=True,
  409. filters={'label': self.labels(one_off=one_off)})
  410. ])
  411. numbers = [c.number for c in containers]
  412. return 1 if not numbers else max(numbers) + 1
  413. def _get_aliases(self, container):
  414. if container.labels.get(LABEL_ONE_OFF) == "True":
  415. return set()
  416. return {self.name, container.short_id}
  417. def _get_links(self, link_to_self):
  418. links = {}
  419. for service, link_name in self.links:
  420. for container in service.containers():
  421. links[link_name or service.name] = container.name
  422. links[container.name] = container.name
  423. links[container.name_without_project] = container.name
  424. if link_to_self:
  425. for container in self.containers():
  426. links[self.name] = container.name
  427. links[container.name] = container.name
  428. links[container.name_without_project] = container.name
  429. for external_link in self.options.get('external_links') or []:
  430. if ':' not in external_link:
  431. link_name = external_link
  432. else:
  433. external_link, link_name = external_link.split(':')
  434. links[link_name] = external_link
  435. return [
  436. (alias, container_name)
  437. for (container_name, alias) in links.items()
  438. ]
  439. def _get_volumes_from(self):
  440. return [build_volume_from(spec) for spec in self.volumes_from]
  441. def _get_container_create_options(
  442. self,
  443. override_options,
  444. number,
  445. one_off=False,
  446. previous_container=None):
  447. add_config_hash = (not one_off and not override_options)
  448. container_options = dict(
  449. (k, self.options[k])
  450. for k in DOCKER_CONFIG_KEYS if k in self.options)
  451. container_options.update(override_options)
  452. if not container_options.get('name'):
  453. container_options['name'] = self.get_container_name(number, one_off)
  454. container_options.setdefault('detach', True)
  455. # If a qualified hostname was given, split it into an
  456. # unqualified hostname and a domainname unless domainname
  457. # was also given explicitly. This matches the behavior of
  458. # the official Docker CLI in that scenario.
  459. if ('hostname' in container_options and
  460. 'domainname' not in container_options and
  461. '.' in container_options['hostname']):
  462. parts = container_options['hostname'].partition('.')
  463. container_options['hostname'] = parts[0]
  464. container_options['domainname'] = parts[2]
  465. if 'ports' in container_options or 'expose' in self.options:
  466. container_options['ports'] = build_container_ports(
  467. container_options,
  468. self.options)
  469. container_options['environment'] = merge_environment(
  470. self.options.get('environment'),
  471. override_options.get('environment'))
  472. binds, affinity = merge_volume_bindings(
  473. container_options.get('volumes') or [],
  474. previous_container)
  475. override_options['binds'] = binds
  476. container_options['environment'].update(affinity)
  477. if 'volumes' in container_options:
  478. container_options['volumes'] = dict(
  479. (v.internal, {}) for v in container_options['volumes'])
  480. container_options['image'] = self.image_name
  481. container_options['labels'] = build_container_labels(
  482. container_options.get('labels', {}),
  483. self.labels(one_off=one_off),
  484. number,
  485. self.config_hash if add_config_hash else None)
  486. # Delete options which are only used when starting
  487. for key in DOCKER_START_KEYS:
  488. container_options.pop(key, None)
  489. container_options['host_config'] = self._get_container_host_config(
  490. override_options,
  491. one_off=one_off)
  492. container_options['environment'] = format_environment(
  493. container_options['environment'])
  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.network_mode.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. shm_size=options.get('shm_size'),
  524. )
  525. def build(self, no_cache=False, pull=False, force_rm=False):
  526. log.info('Building %s' % self.name)
  527. build_opts = self.options.get('build', {})
  528. path = build_opts.get('context')
  529. # python2 os.path() doesn't support unicode, so we need to encode it to
  530. # a byte string
  531. if not six.PY3:
  532. path = path.encode('utf8')
  533. build_output = self.client.build(
  534. path=path,
  535. tag=self.image_name,
  536. stream=True,
  537. rm=True,
  538. forcerm=force_rm,
  539. pull=pull,
  540. nocache=no_cache,
  541. dockerfile=build_opts.get('dockerfile', None),
  542. buildargs=build_opts.get('args', None),
  543. )
  544. try:
  545. all_events = stream_output(build_output, sys.stdout)
  546. except StreamOutputError as e:
  547. raise BuildError(self, six.text_type(e))
  548. # Ensure the HTTP connection is not reused for another
  549. # streaming command, as the Docker daemon can sometimes
  550. # complain about it
  551. self.client.close()
  552. image_id = None
  553. for event in all_events:
  554. if 'stream' in event:
  555. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  556. if match:
  557. image_id = match.group(1)
  558. if image_id is None:
  559. raise BuildError(self, event if all_events else 'Unknown')
  560. return image_id
  561. def can_be_built(self):
  562. return 'build' in self.options
  563. def labels(self, one_off=False):
  564. return [
  565. '{0}={1}'.format(LABEL_PROJECT, self.project),
  566. '{0}={1}'.format(LABEL_SERVICE, self.name),
  567. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  568. ]
  569. @property
  570. def custom_container_name(self):
  571. return self.options.get('container_name')
  572. def get_container_name(self, number, one_off=False):
  573. if self.custom_container_name and not one_off:
  574. return self.custom_container_name
  575. return build_container_name(self.project, self.name, number, one_off)
  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 NetworkMode(object):
  624. """A `standard` network mode (ex: host, bridge)"""
  625. service_name = None
  626. def __init__(self, network_mode):
  627. self.network_mode = network_mode
  628. @property
  629. def id(self):
  630. return self.network_mode
  631. mode = id
  632. class ContainerNetworkMode(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 ServiceNetworkMode(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. affinity = {}
  692. volume_bindings = dict(
  693. build_volume_binding(volume)
  694. for volume in volumes
  695. if volume.external)
  696. if previous_container:
  697. old_volumes = get_container_data_volumes(previous_container, volumes)
  698. warn_on_masked_volume(volumes, old_volumes, previous_container.service)
  699. volume_bindings.update(
  700. build_volume_binding(volume) for volume in old_volumes)
  701. if old_volumes:
  702. affinity = {'affinity:container': '=' + previous_container.id}
  703. return list(volume_bindings.values()), affinity
  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. # Volume was previously a host volume, now it's a container volume
  728. if not mount.get('Name'):
  729. continue
  730. # Copy existing volume from old container
  731. volume = volume._replace(external=mount['Name'])
  732. volumes.append(volume)
  733. return volumes
  734. def warn_on_masked_volume(volumes_option, container_volumes, service):
  735. container_volumes = dict(
  736. (volume.internal, volume.external)
  737. for volume in container_volumes)
  738. for volume in volumes_option:
  739. if (
  740. volume.external and
  741. volume.internal in container_volumes and
  742. container_volumes.get(volume.internal) != volume.external
  743. ):
  744. log.warn((
  745. "Service \"{service}\" is using volume \"{volume}\" from the "
  746. "previous container. Host mapping \"{host_path}\" has no effect. "
  747. "Remove the existing containers (with `docker-compose rm {service}`) "
  748. "to use the host volume mapping."
  749. ).format(
  750. service=service,
  751. volume=volume.internal,
  752. host_path=volume.external))
  753. def build_volume_binding(volume_spec):
  754. return volume_spec.internal, volume_spec.repr()
  755. def build_volume_from(volume_from_spec):
  756. """
  757. volume_from can be either a service or a container. We want to return the
  758. container.id and format it into a string complete with the mode.
  759. """
  760. if isinstance(volume_from_spec.source, Service):
  761. containers = volume_from_spec.source.containers(stopped=True)
  762. if not containers:
  763. return "{}:{}".format(
  764. volume_from_spec.source.create_container().id,
  765. volume_from_spec.mode)
  766. container = containers[0]
  767. return "{}:{}".format(container.id, volume_from_spec.mode)
  768. elif isinstance(volume_from_spec.source, Container):
  769. return "{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)
  770. # Labels
  771. def build_container_labels(label_options, service_labels, number, config_hash):
  772. labels = dict(label_options or {})
  773. labels.update(label.split('=', 1) for label in service_labels)
  774. labels[LABEL_CONTAINER_NUMBER] = str(number)
  775. labels[LABEL_VERSION] = __version__
  776. if config_hash:
  777. log.debug("Added config hash: %s" % config_hash)
  778. labels[LABEL_CONFIG_HASH] = config_hash
  779. return labels
  780. # Ulimits
  781. def build_ulimits(ulimit_config):
  782. if not ulimit_config:
  783. return None
  784. ulimits = []
  785. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  786. if isinstance(soft_hard_values, six.integer_types):
  787. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  788. elif isinstance(soft_hard_values, dict):
  789. ulimit_dict = {'name': limit_name}
  790. ulimit_dict.update(soft_hard_values)
  791. ulimits.append(ulimit_dict)
  792. return ulimits
  793. def get_log_config(logging_dict):
  794. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  795. log_options = logging_dict.get('options', None) if logging_dict else None
  796. return LogConfig(
  797. type=log_driver,
  798. config=log_options
  799. )
  800. # TODO: remove once fix is available in docker-py
  801. def format_environment(environment):
  802. def format_env(key, value):
  803. if value is None:
  804. return key
  805. return '{key}={value}'.format(key=key, value=value)
  806. return [format_env(*item) for item in environment.items()]
  807. # Ports
  808. def build_container_ports(container_options, options):
  809. ports = []
  810. all_ports = container_options.get('ports', []) + options.get('expose', [])
  811. for port_range in all_ports:
  812. internal_range, _ = split_port(port_range)
  813. for port in internal_range:
  814. port = str(port)
  815. if '/' in port:
  816. port = tuple(port.split('/'))
  817. ports.append(port)
  818. return ports