service.py 28 KB

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