service.py 30 KB

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