service.py 30 KB

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