service.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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 and
  440. 'domainname' not in container_options and
  441. '.' 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. logging_dict = options.get('logging', None)
  483. log_config = get_log_config(logging_dict)
  484. return self.client.create_host_config(
  485. links=self._get_links(link_to_self=one_off),
  486. port_bindings=build_port_bindings(options.get('ports') or []),
  487. binds=options.get('binds'),
  488. volumes_from=self._get_volumes_from(),
  489. privileged=options.get('privileged', False),
  490. network_mode=self.net.mode,
  491. devices=options.get('devices'),
  492. dns=options.get('dns'),
  493. dns_search=options.get('dns_search'),
  494. restart_policy=options.get('restart'),
  495. cap_add=options.get('cap_add'),
  496. cap_drop=options.get('cap_drop'),
  497. mem_limit=options.get('mem_limit'),
  498. memswap_limit=options.get('memswap_limit'),
  499. ulimits=build_ulimits(options.get('ulimits')),
  500. log_config=log_config,
  501. extra_hosts=options.get('extra_hosts'),
  502. read_only=options.get('read_only'),
  503. pid_mode=options.get('pid'),
  504. security_opt=options.get('security_opt'),
  505. ipc_mode=options.get('ipc'),
  506. cgroup_parent=options.get('cgroup_parent'),
  507. cpu_quota=options.get('cpu_quota'),
  508. )
  509. def build(self, no_cache=False, pull=False, force_rm=False):
  510. log.info('Building %s' % self.name)
  511. path = self.options['build']
  512. # python2 os.path() doesn't support unicode, so we need to encode it to
  513. # a byte string
  514. if not six.PY3:
  515. path = path.encode('utf8')
  516. build_output = self.client.build(
  517. path=path,
  518. tag=self.image_name,
  519. stream=True,
  520. rm=True,
  521. forcerm=force_rm,
  522. pull=pull,
  523. nocache=no_cache,
  524. dockerfile=self.options.get('dockerfile', None),
  525. )
  526. try:
  527. all_events = stream_output(build_output, sys.stdout)
  528. except StreamOutputError as e:
  529. raise BuildError(self, six.text_type(e))
  530. # Ensure the HTTP connection is not reused for another
  531. # streaming command, as the Docker daemon can sometimes
  532. # complain about it
  533. self.client.close()
  534. image_id = None
  535. for event in all_events:
  536. if 'stream' in event:
  537. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  538. if match:
  539. image_id = match.group(1)
  540. if image_id is None:
  541. raise BuildError(self, event if all_events else 'Unknown')
  542. return image_id
  543. def can_be_built(self):
  544. return 'build' in self.options
  545. @property
  546. def full_name(self):
  547. """
  548. The tag to give to images built for this service.
  549. """
  550. return '%s_%s' % (self.project, self.name)
  551. def labels(self, one_off=False):
  552. return [
  553. '{0}={1}'.format(LABEL_PROJECT, self.project),
  554. '{0}={1}'.format(LABEL_SERVICE, self.name),
  555. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  556. ]
  557. def custom_container_name(self):
  558. return self.options.get('container_name')
  559. def specifies_host_port(self):
  560. def has_host_port(binding):
  561. _, external_bindings = split_port(binding)
  562. # there are no external bindings
  563. if external_bindings is None:
  564. return False
  565. # we only need to check the first binding from the range
  566. external_binding = external_bindings[0]
  567. # non-tuple binding means there is a host port specified
  568. if not isinstance(external_binding, tuple):
  569. return True
  570. # extract actual host port from tuple of (host_ip, host_port)
  571. _, host_port = external_binding
  572. if host_port is not None:
  573. return True
  574. return False
  575. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  576. def pull(self, ignore_pull_failures=False):
  577. if 'image' not in self.options:
  578. return
  579. repo, tag, separator = parse_repository_tag(self.options['image'])
  580. tag = tag or 'latest'
  581. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  582. output = self.client.pull(
  583. repo,
  584. tag=tag,
  585. stream=True,
  586. )
  587. try:
  588. stream_output(output, sys.stdout)
  589. except StreamOutputError as e:
  590. if not ignore_pull_failures:
  591. raise
  592. else:
  593. log.error(six.text_type(e))
  594. class Net(object):
  595. """A `standard` network mode (ex: host, bridge)"""
  596. service_name = None
  597. def __init__(self, net):
  598. self.net = net
  599. @property
  600. def id(self):
  601. return self.net
  602. mode = id
  603. class ContainerNet(object):
  604. """A network mode that uses a container's network stack."""
  605. service_name = None
  606. def __init__(self, container):
  607. self.container = container
  608. @property
  609. def id(self):
  610. return self.container.id
  611. @property
  612. def mode(self):
  613. return 'container:' + self.container.id
  614. class ServiceNet(object):
  615. """A network mode that uses a service's network stack."""
  616. def __init__(self, service):
  617. self.service = service
  618. @property
  619. def id(self):
  620. return self.service.name
  621. service_name = id
  622. @property
  623. def mode(self):
  624. containers = self.service.containers()
  625. if containers:
  626. return 'container:' + containers[0].id
  627. log.warn("Service %s is trying to use reuse the network stack "
  628. "of another service that is not running." % (self.id))
  629. return None
  630. # Names
  631. def build_container_name(project, service, number, one_off=False):
  632. bits = [project, service]
  633. if one_off:
  634. bits.append('run')
  635. return '_'.join(bits + [str(number)])
  636. # Images
  637. def parse_repository_tag(repo_path):
  638. """Splits image identification into base image path, tag/digest
  639. and it's separator.
  640. Example:
  641. >>> parse_repository_tag('user/repo@sha256:digest')
  642. ('user/repo', 'sha256:digest', '@')
  643. >>> parse_repository_tag('user/repo:v1')
  644. ('user/repo', 'v1', ':')
  645. """
  646. tag_separator = ":"
  647. digest_separator = "@"
  648. if digest_separator in repo_path:
  649. repo, tag = repo_path.rsplit(digest_separator, 1)
  650. return repo, tag, digest_separator
  651. repo, tag = repo_path, ""
  652. if tag_separator in repo_path:
  653. repo, tag = repo_path.rsplit(tag_separator, 1)
  654. if "/" in tag:
  655. repo, tag = repo_path, ""
  656. return repo, tag, tag_separator
  657. # Volumes
  658. def merge_volume_bindings(volumes, previous_container):
  659. """Return a list of volume bindings for a container. Container data volumes
  660. are replaced by those from the previous container.
  661. """
  662. volume_bindings = dict(
  663. build_volume_binding(volume)
  664. for volume in volumes
  665. if volume.external)
  666. if previous_container:
  667. data_volumes = get_container_data_volumes(previous_container, volumes)
  668. warn_on_masked_volume(volumes, data_volumes, previous_container.service)
  669. volume_bindings.update(
  670. build_volume_binding(volume) for volume in data_volumes)
  671. return list(volume_bindings.values())
  672. def get_container_data_volumes(container, volumes_option):
  673. """Find the container data volumes that are in `volumes_option`, and return
  674. a mapping of volume bindings for those volumes.
  675. """
  676. volumes = []
  677. volumes_option = volumes_option or []
  678. container_mounts = dict(
  679. (mount['Destination'], mount)
  680. for mount in container.get('Mounts') or {}
  681. )
  682. image_volumes = [
  683. VolumeSpec.parse(volume)
  684. for volume in
  685. container.image_config['ContainerConfig'].get('Volumes') or {}
  686. ]
  687. for volume in set(volumes_option + image_volumes):
  688. # No need to preserve host volumes
  689. if volume.external:
  690. continue
  691. mount = container_mounts.get(volume.internal)
  692. # New volume, doesn't exist in the old container
  693. if not mount:
  694. continue
  695. # Copy existing volume from old container
  696. volume = volume._replace(external=mount['Source'])
  697. volumes.append(volume)
  698. return volumes
  699. def warn_on_masked_volume(volumes_option, container_volumes, service):
  700. container_volumes = dict(
  701. (volume.internal, volume.external)
  702. for volume in container_volumes)
  703. for volume in volumes_option:
  704. if (
  705. volume.external and
  706. volume.internal in container_volumes and
  707. container_volumes.get(volume.internal) != volume.external
  708. ):
  709. log.warn((
  710. "Service \"{service}\" is using volume \"{volume}\" from the "
  711. "previous container. Host mapping \"{host_path}\" has no effect. "
  712. "Remove the existing containers (with `docker-compose rm {service}`) "
  713. "to use the host volume mapping."
  714. ).format(
  715. service=service,
  716. volume=volume.internal,
  717. host_path=volume.external))
  718. def build_volume_binding(volume_spec):
  719. return volume_spec.internal, "{}:{}:{}".format(*volume_spec)
  720. def build_volume_from(volume_from_spec):
  721. """
  722. volume_from can be either a service or a container. We want to return the
  723. container.id and format it into a string complete with the mode.
  724. """
  725. if isinstance(volume_from_spec.source, Service):
  726. containers = volume_from_spec.source.containers(stopped=True)
  727. if not containers:
  728. return ["{}:{}".format(volume_from_spec.source.create_container().id, volume_from_spec.mode)]
  729. container = containers[0]
  730. return ["{}:{}".format(container.id, volume_from_spec.mode)]
  731. elif isinstance(volume_from_spec.source, Container):
  732. return ["{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)]
  733. # Labels
  734. def build_container_labels(label_options, service_labels, number, config_hash):
  735. labels = dict(label_options or {})
  736. labels.update(label.split('=', 1) for label in service_labels)
  737. labels[LABEL_CONTAINER_NUMBER] = str(number)
  738. labels[LABEL_VERSION] = __version__
  739. if config_hash:
  740. log.debug("Added config hash: %s" % config_hash)
  741. labels[LABEL_CONFIG_HASH] = config_hash
  742. return labels
  743. # Ulimits
  744. def build_ulimits(ulimit_config):
  745. if not ulimit_config:
  746. return None
  747. ulimits = []
  748. for limit_name, soft_hard_values in six.iteritems(ulimit_config):
  749. if isinstance(soft_hard_values, six.integer_types):
  750. ulimits.append({'name': limit_name, 'soft': soft_hard_values, 'hard': soft_hard_values})
  751. elif isinstance(soft_hard_values, dict):
  752. ulimit_dict = {'name': limit_name}
  753. ulimit_dict.update(soft_hard_values)
  754. ulimits.append(ulimit_dict)
  755. return ulimits
  756. def get_log_config(logging_dict):
  757. log_driver = logging_dict.get('driver', "") if logging_dict else ""
  758. log_options = logging_dict.get('options', None) if logging_dict else None
  759. return LogConfig(
  760. type=log_driver,
  761. config=log_options
  762. )