service.py 32 KB

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