service.py 31 KB

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