service.py 31 KB

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