service.py 28 KB

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