service.py 29 KB

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