service.py 28 KB

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