service.py 29 KB

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