service.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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. LABEL_CONTAINER_NUMBER,
  15. LABEL_ONE_OFF,
  16. LABEL_PROJECT,
  17. LABEL_SERVICE,
  18. LABEL_VERSION,
  19. LABEL_CONFIG_HASH,
  20. )
  21. from .container import Container
  22. from .legacy import check_for_legacy_containers
  23. from .progress_stream import stream_output, StreamOutputError
  24. from .utils import json_hash
  25. log = logging.getLogger(__name__)
  26. DOCKER_START_KEYS = [
  27. 'cap_add',
  28. 'cap_drop',
  29. 'devices',
  30. 'dns',
  31. 'dns_search',
  32. 'env_file',
  33. 'extra_hosts',
  34. 'read_only',
  35. 'net',
  36. 'log_driver',
  37. 'pid',
  38. 'privileged',
  39. 'restart',
  40. 'volumes_from',
  41. 'security_opt',
  42. ]
  43. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  44. class BuildError(Exception):
  45. def __init__(self, service, reason):
  46. self.service = service
  47. self.reason = reason
  48. class ConfigError(ValueError):
  49. pass
  50. class NeedsBuildError(Exception):
  51. def __init__(self, service):
  52. self.service = service
  53. VolumeSpec = namedtuple('VolumeSpec', 'external internal mode')
  54. ServiceName = namedtuple('ServiceName', 'project service number')
  55. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  56. class Service(object):
  57. def __init__(self, name, client=None, project='default', links=None, external_links=None, volumes_from=None, net=None, **options):
  58. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  59. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  60. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  61. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  62. if 'image' in options and 'build' in options:
  63. 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)
  64. if 'image' not in options and 'build' not in options:
  65. raise ConfigError('Service %s has neither an image nor a build path specified. Exactly one must be provided.' % name)
  66. self.name = name
  67. self.client = client
  68. self.project = project
  69. self.links = links or []
  70. self.external_links = external_links or []
  71. self.volumes_from = volumes_from or []
  72. self.net = net or None
  73. self.options = options
  74. def containers(self, stopped=False, one_off=False):
  75. containers = [
  76. Container.from_ps(self.client, container)
  77. for container in self.client.containers(
  78. all=stopped,
  79. filters={'label': self.labels(one_off=one_off)})]
  80. if not containers:
  81. check_for_legacy_containers(
  82. self.client,
  83. self.project,
  84. [self.name],
  85. stopped=stopped,
  86. one_off=one_off)
  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 converge(self,
  207. allow_recreate=True,
  208. smart_recreate=False,
  209. insecure_registry=False,
  210. do_build=True):
  211. """
  212. If a container for this service doesn't exist, create and start one. If there are
  213. any, stop them, create+start new ones, and remove the old containers.
  214. """
  215. plan = self.convergence_plan(
  216. allow_recreate=allow_recreate,
  217. smart_recreate=smart_recreate,
  218. )
  219. return self.execute_convergence_plan(
  220. plan,
  221. insecure_registry=insecure_registry,
  222. do_build=do_build,
  223. )
  224. def convergence_plan(self,
  225. allow_recreate=True,
  226. smart_recreate=False):
  227. containers = self.containers(stopped=True)
  228. if not containers:
  229. return ConvergencePlan('create', [])
  230. if smart_recreate and not self._containers_have_diverged(containers):
  231. stopped = [c for c in containers if not c.is_running]
  232. if stopped:
  233. return ConvergencePlan('start', stopped)
  234. return ConvergencePlan('noop', containers)
  235. if not allow_recreate:
  236. return ConvergencePlan('start', containers)
  237. return ConvergencePlan('recreate', containers)
  238. def _containers_have_diverged(self, containers):
  239. config_hash = self.config_hash()
  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. (action, containers) = plan
  255. if action == 'create':
  256. container = self.create_container(
  257. insecure_registry=insecure_registry,
  258. do_build=do_build,
  259. )
  260. self.start_container(container)
  261. return [container]
  262. elif action == 'recreate':
  263. return [
  264. self.recreate_container(
  265. c,
  266. insecure_registry=insecure_registry,
  267. )
  268. for c in containers
  269. ]
  270. elif action == 'start':
  271. for c in containers:
  272. self.start_container_if_stopped(c)
  273. return containers
  274. elif action == 'noop':
  275. for c in containers:
  276. log.info("%s is up-to-date" % c.name)
  277. return containers
  278. else:
  279. raise Exception("Invalid action: {}".format(action))
  280. def recreate_container(self,
  281. container,
  282. insecure_registry=False):
  283. """Recreate a container.
  284. The original container is renamed to a temporary name so that data
  285. volumes can be copied to the new container, before the original
  286. container is removed.
  287. """
  288. log.info("Recreating %s..." % container.name)
  289. try:
  290. container.stop()
  291. except APIError as e:
  292. if (e.response.status_code == 500
  293. and e.explanation
  294. and 'no such process' in str(e.explanation)):
  295. pass
  296. else:
  297. raise
  298. # Use a hopefully unique container name by prepending the short id
  299. self.client.rename(
  300. container.id,
  301. '%s_%s' % (container.short_id, container.name))
  302. new_container = self.create_container(
  303. insecure_registry=insecure_registry,
  304. do_build=False,
  305. previous_container=container,
  306. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  307. quiet=True,
  308. )
  309. self.start_container(new_container)
  310. container.remove()
  311. return new_container
  312. def start_container_if_stopped(self, container):
  313. if container.is_running:
  314. return container
  315. else:
  316. log.info("Starting %s..." % container.name)
  317. return self.start_container(container)
  318. def start_container(self, container):
  319. container.start()
  320. return container
  321. def config_hash(self):
  322. return json_hash(self.config_dict())
  323. def config_dict(self):
  324. return {
  325. 'options': self.options,
  326. 'image_id': self.image()['Id'],
  327. }
  328. def get_dependency_names(self):
  329. net_name = self.get_net_name()
  330. return (self.get_linked_names() +
  331. self.get_volumes_from_names() +
  332. ([net_name] if net_name else []))
  333. def get_linked_names(self):
  334. return [s.name for (s, _) in self.links]
  335. def get_volumes_from_names(self):
  336. return [s.name for s in self.volumes_from if isinstance(s, Service)]
  337. def get_net_name(self):
  338. if isinstance(self.net, Service):
  339. return self.net.name
  340. else:
  341. return
  342. def get_container_name(self, number, one_off=False):
  343. # TODO: Implement issue #652 here
  344. return build_container_name(self.project, self.name, number, one_off)
  345. # TODO: this would benefit from github.com/docker/docker/pull/11943
  346. # to remove the need to inspect every container
  347. def _next_container_number(self, one_off=False):
  348. numbers = [
  349. Container.from_ps(self.client, container).number
  350. for container in self.client.containers(
  351. all=True,
  352. filters={'label': self.labels(one_off=one_off)})
  353. ]
  354. return 1 if not numbers else max(numbers) + 1
  355. def _get_links(self, link_to_self):
  356. links = []
  357. for service, link_name in self.links:
  358. for container in service.containers():
  359. links.append((container.name, link_name or service.name))
  360. links.append((container.name, container.name))
  361. links.append((container.name, container.name_without_project))
  362. if link_to_self:
  363. for container in self.containers():
  364. links.append((container.name, self.name))
  365. links.append((container.name, container.name))
  366. links.append((container.name, container.name_without_project))
  367. for external_link in self.external_links:
  368. if ':' not in external_link:
  369. link_name = external_link
  370. else:
  371. external_link, link_name = external_link.split(':')
  372. links.append((external_link, link_name))
  373. return links
  374. def _get_volumes_from(self):
  375. volumes_from = []
  376. for volume_source in self.volumes_from:
  377. if isinstance(volume_source, Service):
  378. containers = volume_source.containers(stopped=True)
  379. if not containers:
  380. volumes_from.append(volume_source.create_container().id)
  381. else:
  382. volumes_from.extend(map(attrgetter('id'), containers))
  383. elif isinstance(volume_source, Container):
  384. volumes_from.append(volume_source.id)
  385. return volumes_from
  386. def _get_net(self):
  387. if not self.net:
  388. return "bridge"
  389. if isinstance(self.net, Service):
  390. containers = self.net.containers()
  391. if len(containers) > 0:
  392. net = 'container:' + containers[0].id
  393. else:
  394. log.warning("Warning: Service %s is trying to use reuse the network stack "
  395. "of another service that is not running." % (self.net.name))
  396. net = None
  397. elif isinstance(self.net, Container):
  398. net = 'container:' + self.net.id
  399. else:
  400. net = self.net
  401. return net
  402. def _get_container_create_options(
  403. self,
  404. override_options,
  405. number,
  406. one_off=False,
  407. previous_container=None):
  408. add_config_hash = (not one_off and not override_options)
  409. container_options = dict(
  410. (k, self.options[k])
  411. for k in DOCKER_CONFIG_KEYS if k in self.options)
  412. container_options.update(override_options)
  413. container_options['name'] = self.get_container_name(number, one_off)
  414. if add_config_hash:
  415. config_hash = self.config_hash()
  416. if 'labels' not in container_options:
  417. container_options['labels'] = {}
  418. container_options['labels'][LABEL_CONFIG_HASH] = config_hash
  419. log.debug("Added config hash: %s" % config_hash)
  420. if 'detach' not in container_options:
  421. container_options['detach'] = True
  422. # If a qualified hostname was given, split it into an
  423. # unqualified hostname and a domainname unless domainname
  424. # was also given explicitly. This matches the behavior of
  425. # the official Docker CLI in that scenario.
  426. if ('hostname' in container_options
  427. and 'domainname' not in container_options
  428. and '.' in container_options['hostname']):
  429. parts = container_options['hostname'].partition('.')
  430. container_options['hostname'] = parts[0]
  431. container_options['domainname'] = parts[2]
  432. if 'ports' in container_options or 'expose' in self.options:
  433. ports = []
  434. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  435. for port in all_ports:
  436. port = str(port)
  437. if ':' in port:
  438. port = port.split(':')[-1]
  439. if '/' in port:
  440. port = tuple(port.split('/'))
  441. ports.append(port)
  442. container_options['ports'] = ports
  443. override_options['binds'] = merge_volume_bindings(
  444. container_options.get('volumes') or [],
  445. previous_container)
  446. if 'volumes' in container_options:
  447. container_options['volumes'] = dict(
  448. (parse_volume_spec(v).internal, {})
  449. for v in container_options['volumes'])
  450. container_options['environment'] = merge_environment(
  451. self.options.get('environment'),
  452. override_options.get('environment'))
  453. if previous_container:
  454. container_options['environment']['affinity:container'] = ('=' + previous_container.id)
  455. container_options['image'] = self.image_name
  456. container_options['labels'] = build_container_labels(
  457. container_options.get('labels', {}),
  458. self.labels(one_off=one_off),
  459. number)
  460. # Delete options which are only used when starting
  461. for key in DOCKER_START_KEYS:
  462. container_options.pop(key, None)
  463. container_options['host_config'] = self._get_container_host_config(
  464. override_options,
  465. one_off=one_off)
  466. return container_options
  467. def _get_container_host_config(self, override_options, one_off=False):
  468. options = dict(self.options, **override_options)
  469. port_bindings = build_port_bindings(options.get('ports') or [])
  470. privileged = options.get('privileged', False)
  471. cap_add = options.get('cap_add', None)
  472. cap_drop = options.get('cap_drop', None)
  473. log_config = LogConfig(type=options.get('log_driver', 'json-file'))
  474. pid = options.get('pid', None)
  475. security_opt = options.get('security_opt', None)
  476. dns = options.get('dns', None)
  477. if isinstance(dns, six.string_types):
  478. dns = [dns]
  479. dns_search = options.get('dns_search', None)
  480. if isinstance(dns_search, six.string_types):
  481. dns_search = [dns_search]
  482. restart = parse_restart_spec(options.get('restart', None))
  483. extra_hosts = build_extra_hosts(options.get('extra_hosts', None))
  484. read_only = options.get('read_only', None)
  485. devices = options.get('devices', None)
  486. return create_host_config(
  487. links=self._get_links(link_to_self=one_off),
  488. port_bindings=port_bindings,
  489. binds=options.get('binds'),
  490. volumes_from=self._get_volumes_from(),
  491. privileged=privileged,
  492. network_mode=self._get_net(),
  493. devices=devices,
  494. dns=dns,
  495. dns_search=dns_search,
  496. restart_policy=restart,
  497. cap_add=cap_add,
  498. cap_drop=cap_drop,
  499. log_config=log_config,
  500. extra_hosts=extra_hosts,
  501. read_only=read_only,
  502. pid_mode=pid,
  503. security_opt=security_opt
  504. )
  505. def build(self, no_cache=False):
  506. log.info('Building %s...' % self.name)
  507. path = six.binary_type(self.options['build'])
  508. build_output = self.client.build(
  509. path=path,
  510. tag=self.image_name,
  511. stream=True,
  512. rm=True,
  513. nocache=no_cache,
  514. dockerfile=self.options.get('dockerfile', None),
  515. )
  516. try:
  517. all_events = stream_output(build_output, sys.stdout)
  518. except StreamOutputError as e:
  519. raise BuildError(self, unicode(e))
  520. # Ensure the HTTP connection is not reused for another
  521. # streaming command, as the Docker daemon can sometimes
  522. # complain about it
  523. self.client.close()
  524. image_id = None
  525. for event in all_events:
  526. if 'stream' in event:
  527. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  528. if match:
  529. image_id = match.group(1)
  530. if image_id is None:
  531. raise BuildError(self, event if all_events else 'Unknown')
  532. return image_id
  533. def can_be_built(self):
  534. return 'build' in self.options
  535. @property
  536. def full_name(self):
  537. """
  538. The tag to give to images built for this service.
  539. """
  540. return '%s_%s' % (self.project, self.name)
  541. def labels(self, one_off=False):
  542. return [
  543. '{0}={1}'.format(LABEL_PROJECT, self.project),
  544. '{0}={1}'.format(LABEL_SERVICE, self.name),
  545. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  546. ]
  547. def can_be_scaled(self):
  548. for port in self.options.get('ports', []):
  549. if ':' in str(port):
  550. return False
  551. return True
  552. def pull(self, insecure_registry=False):
  553. if 'image' not in self.options:
  554. return
  555. repo, tag = parse_repository_tag(self.options['image'])
  556. tag = tag or 'latest'
  557. log.info('Pulling %s (%s:%s)...' % (self.name, repo, tag))
  558. output = self.client.pull(
  559. repo,
  560. tag=tag,
  561. stream=True,
  562. insecure_registry=insecure_registry)
  563. stream_output(output, sys.stdout)
  564. # Names
  565. def build_container_name(project, service, number, one_off=False):
  566. bits = [project, service]
  567. if one_off:
  568. bits.append('run')
  569. return '_'.join(bits + [str(number)])
  570. # Images
  571. def parse_repository_tag(s):
  572. if ":" not in s:
  573. return s, ""
  574. repo, tag = s.rsplit(":", 1)
  575. if "/" in tag:
  576. return s, ""
  577. return repo, tag
  578. # Volumes
  579. def merge_volume_bindings(volumes_option, previous_container):
  580. """Return a list of volume bindings for a container. Container data volumes
  581. are replaced by those from the previous container.
  582. """
  583. volume_bindings = dict(
  584. build_volume_binding(parse_volume_spec(volume))
  585. for volume in volumes_option or []
  586. if ':' in volume)
  587. if previous_container:
  588. volume_bindings.update(
  589. get_container_data_volumes(previous_container, volumes_option))
  590. return volume_bindings.values()
  591. def get_container_data_volumes(container, volumes_option):
  592. """Find the container data volumes that are in `volumes_option`, and return
  593. a mapping of volume bindings for those volumes.
  594. """
  595. volumes = []
  596. volumes_option = volumes_option or []
  597. container_volumes = container.get('Volumes') or {}
  598. image_volumes = container.image_config['ContainerConfig'].get('Volumes') or {}
  599. for volume in set(volumes_option + image_volumes.keys()):
  600. volume = parse_volume_spec(volume)
  601. # No need to preserve host volumes
  602. if volume.external:
  603. continue
  604. volume_path = container_volumes.get(volume.internal)
  605. # New volume, doesn't exist in the old container
  606. if not volume_path:
  607. continue
  608. # Copy existing volume from old container
  609. volume = volume._replace(external=volume_path)
  610. volumes.append(build_volume_binding(volume))
  611. return dict(volumes)
  612. def build_volume_binding(volume_spec):
  613. return volume_spec.internal, "{}:{}:{}".format(*volume_spec)
  614. def parse_volume_spec(volume_config):
  615. parts = volume_config.split(':')
  616. if len(parts) > 3:
  617. raise ConfigError("Volume %s has incorrect format, should be "
  618. "external:internal[:mode]" % volume_config)
  619. if len(parts) == 1:
  620. return VolumeSpec(None, parts[0], 'rw')
  621. if len(parts) == 2:
  622. parts.append('rw')
  623. external, internal, mode = parts
  624. if mode not in ('rw', 'ro'):
  625. raise ConfigError("Volume %s has invalid mode (%s), should be "
  626. "one of: rw, ro." % (volume_config, mode))
  627. return VolumeSpec(external, internal, mode)
  628. # Ports
  629. def build_port_bindings(ports):
  630. port_bindings = {}
  631. for port in ports:
  632. internal_port, external = split_port(port)
  633. if internal_port in port_bindings:
  634. port_bindings[internal_port].append(external)
  635. else:
  636. port_bindings[internal_port] = [external]
  637. return port_bindings
  638. def split_port(port):
  639. parts = str(port).split(':')
  640. if not 1 <= len(parts) <= 3:
  641. raise ConfigError('Invalid port "%s", should be '
  642. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  643. if len(parts) == 1:
  644. internal_port, = parts
  645. return internal_port, None
  646. if len(parts) == 2:
  647. external_port, internal_port = parts
  648. return internal_port, external_port
  649. external_ip, external_port, internal_port = parts
  650. return internal_port, (external_ip, external_port or None)
  651. # Labels
  652. def build_container_labels(label_options, service_labels, number, one_off=False):
  653. labels = label_options or {}
  654. labels.update(label.split('=', 1) for label in service_labels)
  655. labels[LABEL_CONTAINER_NUMBER] = str(number)
  656. labels[LABEL_VERSION] = __version__
  657. return labels
  658. # Restart policy
  659. def parse_restart_spec(restart_config):
  660. if not restart_config:
  661. return None
  662. parts = restart_config.split(':')
  663. if len(parts) > 2:
  664. raise ConfigError("Restart %s has incorrect format, should be "
  665. "mode[:max_retry]" % restart_config)
  666. if len(parts) == 2:
  667. name, max_retry_count = parts
  668. else:
  669. name, = parts
  670. max_retry_count = 0
  671. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  672. # Extra hosts
  673. def build_extra_hosts(extra_hosts_config):
  674. if not extra_hosts_config:
  675. return {}
  676. if isinstance(extra_hosts_config, list):
  677. extra_hosts_dict = {}
  678. for extra_hosts_line in extra_hosts_config:
  679. if not isinstance(extra_hosts_line, six.string_types):
  680. raise ConfigError(
  681. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  682. extra_hosts_config
  683. )
  684. host, ip = extra_hosts_line.split(':')
  685. extra_hosts_dict.update({host.strip(): ip.strip()})
  686. extra_hosts_config = extra_hosts_dict
  687. if isinstance(extra_hosts_config, dict):
  688. return extra_hosts_config
  689. raise ConfigError(
  690. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  691. extra_hosts_config
  692. )