service.py 31 KB

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