service.py 29 KB

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