service.py 30 KB

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