service.py 29 KB

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