service.py 35 KB

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