service.py 28 KB

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