service.py 30 KB

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