service.py 30 KB

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