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