service.py 31 KB

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