service.py 28 KB

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