service.py 30 KB

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