service.py 30 KB

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