service.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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 'detach' not in container_options:
  460. container_options['detach'] = True
  461. # If a qualified hostname was given, split it into an
  462. # unqualified hostname and a domainname unless domainname
  463. # was also given explicitly. This matches the behavior of
  464. # the official Docker CLI in that scenario.
  465. if ('hostname' in container_options
  466. and 'domainname' not in container_options
  467. and '.' in container_options['hostname']):
  468. parts = container_options['hostname'].partition('.')
  469. container_options['hostname'] = parts[0]
  470. container_options['domainname'] = parts[2]
  471. if 'ports' in container_options or 'expose' in self.options:
  472. ports = []
  473. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  474. for port in all_ports:
  475. port = str(port)
  476. if ':' in port:
  477. port = port.split(':')[-1]
  478. if '/' in port:
  479. port = tuple(port.split('/'))
  480. ports.append(port)
  481. container_options['ports'] = ports
  482. override_options['binds'] = merge_volume_bindings(
  483. container_options.get('volumes') or [],
  484. previous_container)
  485. if 'volumes' in container_options:
  486. container_options['volumes'] = dict(
  487. (parse_volume_spec(v).internal, {})
  488. for v in container_options['volumes'])
  489. container_options['environment'] = merge_environment(
  490. self.options.get('environment'),
  491. override_options.get('environment'))
  492. if previous_container:
  493. container_options['environment']['affinity:container'] = ('=' + previous_container.id)
  494. container_options['image'] = self.image_name
  495. container_options['labels'] = build_container_labels(
  496. container_options.get('labels', {}),
  497. self.labels(one_off=one_off),
  498. number,
  499. self.config_hash() if add_config_hash else None)
  500. # Delete options which are only used when starting
  501. for key in DOCKER_START_KEYS:
  502. container_options.pop(key, None)
  503. container_options['host_config'] = self._get_container_host_config(
  504. override_options,
  505. one_off=one_off)
  506. return container_options
  507. def _get_container_host_config(self, override_options, one_off=False):
  508. options = dict(self.options, **override_options)
  509. port_bindings = build_port_bindings(options.get('ports') or [])
  510. privileged = options.get('privileged', False)
  511. cap_add = options.get('cap_add', None)
  512. cap_drop = options.get('cap_drop', None)
  513. log_config = LogConfig(
  514. type=options.get('log_driver', 'json-file'),
  515. config=options.get('log_opt', None)
  516. )
  517. pid = options.get('pid', None)
  518. security_opt = options.get('security_opt', None)
  519. dns = options.get('dns', None)
  520. if isinstance(dns, six.string_types):
  521. dns = [dns]
  522. dns_search = options.get('dns_search', None)
  523. if isinstance(dns_search, six.string_types):
  524. dns_search = [dns_search]
  525. restart = parse_restart_spec(options.get('restart', None))
  526. extra_hosts = build_extra_hosts(options.get('extra_hosts', None))
  527. read_only = options.get('read_only', None)
  528. devices = options.get('devices', None)
  529. return create_host_config(
  530. links=self._get_links(link_to_self=one_off),
  531. port_bindings=port_bindings,
  532. binds=options.get('binds'),
  533. volumes_from=self._get_volumes_from(),
  534. privileged=privileged,
  535. network_mode=self.net.mode,
  536. devices=devices,
  537. dns=dns,
  538. dns_search=dns_search,
  539. restart_policy=restart,
  540. cap_add=cap_add,
  541. cap_drop=cap_drop,
  542. mem_limit=options.get('mem_limit'),
  543. memswap_limit=options.get('memswap_limit'),
  544. log_config=log_config,
  545. extra_hosts=extra_hosts,
  546. read_only=read_only,
  547. pid_mode=pid,
  548. security_opt=security_opt
  549. )
  550. def build(self, no_cache=False):
  551. log.info('Building %s...' % self.name)
  552. path = six.binary_type(self.options['build'])
  553. build_output = self.client.build(
  554. path=path,
  555. tag=self.image_name,
  556. stream=True,
  557. rm=True,
  558. pull=False,
  559. nocache=no_cache,
  560. dockerfile=self.options.get('dockerfile', None),
  561. )
  562. try:
  563. all_events = stream_output(build_output, sys.stdout)
  564. except StreamOutputError as e:
  565. raise BuildError(self, unicode(e))
  566. # Ensure the HTTP connection is not reused for another
  567. # streaming command, as the Docker daemon can sometimes
  568. # complain about it
  569. self.client.close()
  570. image_id = None
  571. for event in all_events:
  572. if 'stream' in event:
  573. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  574. if match:
  575. image_id = match.group(1)
  576. if image_id is None:
  577. raise BuildError(self, event if all_events else 'Unknown')
  578. return image_id
  579. def can_be_built(self):
  580. return 'build' in self.options
  581. @property
  582. def full_name(self):
  583. """
  584. The tag to give to images built for this service.
  585. """
  586. return '%s_%s' % (self.project, self.name)
  587. def labels(self, one_off=False):
  588. return [
  589. '{0}={1}'.format(LABEL_PROJECT, self.project),
  590. '{0}={1}'.format(LABEL_SERVICE, self.name),
  591. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  592. ]
  593. def custom_container_name(self):
  594. return self.options.get('container_name')
  595. def specifies_host_port(self):
  596. for port in self.options.get('ports', []):
  597. if ':' in str(port):
  598. return True
  599. return False
  600. def pull(self):
  601. if 'image' not in self.options:
  602. return
  603. repo, tag = parse_repository_tag(self.options['image'])
  604. tag = tag or 'latest'
  605. log.info('Pulling %s (%s:%s)...' % (self.name, repo, tag))
  606. output = self.client.pull(
  607. repo,
  608. tag=tag,
  609. stream=True,
  610. )
  611. stream_output(output, sys.stdout)
  612. class Net(object):
  613. """A `standard` network mode (ex: host, bridge)"""
  614. service_name = None
  615. def __init__(self, net):
  616. self.net = net
  617. @property
  618. def id(self):
  619. return self.net
  620. mode = id
  621. class ContainerNet(object):
  622. """A network mode that uses a container's network stack."""
  623. service_name = None
  624. def __init__(self, container):
  625. self.container = container
  626. @property
  627. def id(self):
  628. return self.container.id
  629. @property
  630. def mode(self):
  631. return 'container:' + self.container.id
  632. class ServiceNet(object):
  633. """A network mode that uses a service's network stack."""
  634. def __init__(self, service):
  635. self.service = service
  636. @property
  637. def id(self):
  638. return self.service.name
  639. service_name = id
  640. @property
  641. def mode(self):
  642. containers = self.service.containers()
  643. if containers:
  644. return 'container:' + containers[0].id
  645. log.warn("Warning: Service %s is trying to use reuse the network stack "
  646. "of another service that is not running." % (self.id))
  647. return None
  648. # Names
  649. def build_container_name(project, service, number, one_off=False):
  650. bits = [project, service]
  651. if one_off:
  652. bits.append('run')
  653. return '_'.join(bits + [str(number)])
  654. # Images
  655. def parse_repository_tag(s):
  656. if ":" not in s:
  657. return s, ""
  658. repo, tag = s.rsplit(":", 1)
  659. if "/" in tag:
  660. return s, ""
  661. return repo, tag
  662. # Volumes
  663. def merge_volume_bindings(volumes_option, previous_container):
  664. """Return a list of volume bindings for a container. Container data volumes
  665. are replaced by those from the previous container.
  666. """
  667. volume_bindings = dict(
  668. build_volume_binding(parse_volume_spec(volume))
  669. for volume in volumes_option or []
  670. if ':' in volume)
  671. if previous_container:
  672. volume_bindings.update(
  673. get_container_data_volumes(previous_container, volumes_option))
  674. return volume_bindings.values()
  675. def get_container_data_volumes(container, volumes_option):
  676. """Find the container data volumes that are in `volumes_option`, and return
  677. a mapping of volume bindings for those volumes.
  678. """
  679. volumes = []
  680. volumes_option = volumes_option or []
  681. container_volumes = container.get('Volumes') or {}
  682. image_volumes = container.image_config['ContainerConfig'].get('Volumes') or {}
  683. for volume in set(volumes_option + image_volumes.keys()):
  684. volume = parse_volume_spec(volume)
  685. # No need to preserve host volumes
  686. if volume.external:
  687. continue
  688. volume_path = container_volumes.get(volume.internal)
  689. # New volume, doesn't exist in the old container
  690. if not volume_path:
  691. continue
  692. # Copy existing volume from old container
  693. volume = volume._replace(external=volume_path)
  694. volumes.append(build_volume_binding(volume))
  695. return dict(volumes)
  696. def build_volume_binding(volume_spec):
  697. return volume_spec.internal, "{}:{}:{}".format(*volume_spec)
  698. def parse_volume_spec(volume_config):
  699. parts = volume_config.split(':')
  700. if len(parts) > 3:
  701. raise ConfigError("Volume %s has incorrect format, should be "
  702. "external:internal[:mode]" % volume_config)
  703. if len(parts) == 1:
  704. external = None
  705. internal = os.path.normpath(parts[0])
  706. else:
  707. external = os.path.normpath(parts[0])
  708. internal = os.path.normpath(parts[1])
  709. mode = parts[2] if len(parts) == 3 else 'rw'
  710. return VolumeSpec(external, internal, mode)
  711. # Ports
  712. def build_port_bindings(ports):
  713. port_bindings = {}
  714. for port in ports:
  715. internal_port, external = split_port(port)
  716. if internal_port in port_bindings:
  717. port_bindings[internal_port].append(external)
  718. else:
  719. port_bindings[internal_port] = [external]
  720. return port_bindings
  721. def split_port(port):
  722. parts = str(port).split(':')
  723. if not 1 <= len(parts) <= 3:
  724. raise ConfigError('Invalid port "%s", should be '
  725. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  726. if len(parts) == 1:
  727. internal_port, = parts
  728. return internal_port, None
  729. if len(parts) == 2:
  730. external_port, internal_port = parts
  731. return internal_port, external_port
  732. external_ip, external_port, internal_port = parts
  733. return internal_port, (external_ip, external_port or None)
  734. # Labels
  735. def build_container_labels(label_options, service_labels, number, config_hash):
  736. labels = dict(label_options or {})
  737. labels.update(label.split('=', 1) for label in service_labels)
  738. labels[LABEL_CONTAINER_NUMBER] = str(number)
  739. labels[LABEL_VERSION] = __version__
  740. if config_hash:
  741. log.debug("Added config hash: %s" % config_hash)
  742. labels[LABEL_CONFIG_HASH] = config_hash
  743. return labels
  744. # Restart policy
  745. def parse_restart_spec(restart_config):
  746. if not restart_config:
  747. return None
  748. parts = restart_config.split(':')
  749. if len(parts) > 2:
  750. raise ConfigError("Restart %s has incorrect format, should be "
  751. "mode[:max_retry]" % restart_config)
  752. if len(parts) == 2:
  753. name, max_retry_count = parts
  754. else:
  755. name, = parts
  756. max_retry_count = 0
  757. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  758. # Extra hosts
  759. def build_extra_hosts(extra_hosts_config):
  760. if not extra_hosts_config:
  761. return {}
  762. if isinstance(extra_hosts_config, list):
  763. extra_hosts_dict = {}
  764. for extra_hosts_line in extra_hosts_config:
  765. if not isinstance(extra_hosts_line, six.string_types):
  766. raise ConfigError(
  767. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  768. extra_hosts_config
  769. )
  770. host, ip = extra_hosts_line.split(':')
  771. extra_hosts_dict.update({host.strip(): ip.strip()})
  772. extra_hosts_config = extra_hosts_dict
  773. if isinstance(extra_hosts_config, dict):
  774. return extra_hosts_config
  775. raise ConfigError(
  776. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  777. extra_hosts_config
  778. )