project.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import datetime
  4. import logging
  5. import operator
  6. import re
  7. from functools import reduce
  8. import enum
  9. import six
  10. from docker.errors import APIError
  11. from . import parallel
  12. from .config import ConfigurationError
  13. from .config.config import V1
  14. from .config.sort_services import get_container_name_from_network_mode
  15. from .config.sort_services import get_service_name_from_network_mode
  16. from .const import IMAGE_EVENTS
  17. from .const import LABEL_ONE_OFF
  18. from .const import LABEL_PROJECT
  19. from .const import LABEL_SERVICE
  20. from .container import Container
  21. from .network import build_networks
  22. from .network import get_networks
  23. from .network import ProjectNetworks
  24. from .service import BuildAction
  25. from .service import ContainerNetworkMode
  26. from .service import ContainerPidMode
  27. from .service import ConvergenceStrategy
  28. from .service import NetworkMode
  29. from .service import PidMode
  30. from .service import Service
  31. from .service import ServiceNetworkMode
  32. from .service import ServicePidMode
  33. from .utils import microseconds_from_time_nano
  34. from .utils import truncate_string
  35. from .volume import ProjectVolumes
  36. log = logging.getLogger(__name__)
  37. @enum.unique
  38. class OneOffFilter(enum.Enum):
  39. include = 0
  40. exclude = 1
  41. only = 2
  42. @classmethod
  43. def update_labels(cls, value, labels):
  44. if value == cls.only:
  45. labels.append('{0}={1}'.format(LABEL_ONE_OFF, "True"))
  46. elif value == cls.exclude:
  47. labels.append('{0}={1}'.format(LABEL_ONE_OFF, "False"))
  48. elif value == cls.include:
  49. pass
  50. else:
  51. raise ValueError("Invalid value for one_off: {}".format(repr(value)))
  52. class Project(object):
  53. """
  54. A collection of services.
  55. """
  56. def __init__(self, name, services, client, networks=None, volumes=None, config_version=None):
  57. self.name = name
  58. self.services = services
  59. self.client = client
  60. self.volumes = volumes or ProjectVolumes({})
  61. self.networks = networks or ProjectNetworks({}, False)
  62. self.config_version = config_version
  63. def labels(self, one_off=OneOffFilter.exclude, legacy=False):
  64. name = self.name
  65. if legacy:
  66. name = re.sub(r'[_-]', '', name)
  67. labels = ['{0}={1}'.format(LABEL_PROJECT, name)]
  68. OneOffFilter.update_labels(one_off, labels)
  69. return labels
  70. @classmethod
  71. def from_config(cls, name, config_data, client, default_platform=None):
  72. """
  73. Construct a Project from a config.Config object.
  74. """
  75. use_networking = (config_data.version and config_data.version != V1)
  76. networks = build_networks(name, config_data, client)
  77. project_networks = ProjectNetworks.from_services(
  78. config_data.services,
  79. networks,
  80. use_networking)
  81. volumes = ProjectVolumes.from_config(name, config_data, client)
  82. project = cls(name, [], client, project_networks, volumes, config_data.version)
  83. for service_dict in config_data.services:
  84. service_dict = dict(service_dict)
  85. if use_networking:
  86. service_networks = get_networks(service_dict, networks)
  87. else:
  88. service_networks = {}
  89. service_dict.pop('networks', None)
  90. links = project.get_links(service_dict)
  91. network_mode = project.get_network_mode(
  92. service_dict, list(service_networks.keys())
  93. )
  94. pid_mode = project.get_pid_mode(service_dict)
  95. volumes_from = get_volumes_from(project, service_dict)
  96. if config_data.version != V1:
  97. service_dict['volumes'] = [
  98. volumes.namespace_spec(volume_spec)
  99. for volume_spec in service_dict.get('volumes', [])
  100. ]
  101. secrets = get_secrets(
  102. service_dict['name'],
  103. service_dict.pop('secrets', None) or [],
  104. config_data.secrets)
  105. project.services.append(
  106. Service(
  107. service_dict.pop('name'),
  108. client=client,
  109. project=name,
  110. use_networking=use_networking,
  111. networks=service_networks,
  112. links=links,
  113. network_mode=network_mode,
  114. volumes_from=volumes_from,
  115. secrets=secrets,
  116. pid_mode=pid_mode,
  117. platform=service_dict.pop('platform', None),
  118. default_platform=default_platform,
  119. **service_dict)
  120. )
  121. return project
  122. @property
  123. def service_names(self):
  124. return [service.name for service in self.services]
  125. def get_service(self, name):
  126. """
  127. Retrieve a service by name. Raises NoSuchService
  128. if the named service does not exist.
  129. """
  130. for service in self.services:
  131. if service.name == name:
  132. return service
  133. raise NoSuchService(name)
  134. def validate_service_names(self, service_names):
  135. """
  136. Validate that the given list of service names only contains valid
  137. services. Raises NoSuchService if one of the names is invalid.
  138. """
  139. valid_names = self.service_names
  140. for name in service_names:
  141. if name not in valid_names:
  142. raise NoSuchService(name)
  143. def get_services(self, service_names=None, include_deps=False):
  144. """
  145. Returns a list of this project's services filtered
  146. by the provided list of names, or all services if service_names is None
  147. or [].
  148. If include_deps is specified, returns a list including the dependencies for
  149. service_names, in order of dependency.
  150. Preserves the original order of self.services where possible,
  151. reordering as needed to resolve dependencies.
  152. Raises NoSuchService if any of the named services do not exist.
  153. """
  154. if service_names is None or len(service_names) == 0:
  155. service_names = self.service_names
  156. unsorted = [self.get_service(name) for name in service_names]
  157. services = [s for s in self.services if s in unsorted]
  158. if include_deps:
  159. services = reduce(self._inject_deps, services, [])
  160. uniques = []
  161. [uniques.append(s) for s in services if s not in uniques]
  162. return uniques
  163. def get_services_without_duplicate(self, service_names=None, include_deps=False):
  164. services = self.get_services(service_names, include_deps)
  165. for service in services:
  166. service.remove_duplicate_containers()
  167. return services
  168. def get_links(self, service_dict):
  169. links = []
  170. if 'links' in service_dict:
  171. for link in service_dict.get('links', []):
  172. if ':' in link:
  173. service_name, link_name = link.split(':', 1)
  174. else:
  175. service_name, link_name = link, None
  176. try:
  177. links.append((self.get_service(service_name), link_name))
  178. except NoSuchService:
  179. raise ConfigurationError(
  180. 'Service "%s" has a link to service "%s" which does not '
  181. 'exist.' % (service_dict['name'], service_name))
  182. del service_dict['links']
  183. return links
  184. def get_network_mode(self, service_dict, networks):
  185. network_mode = service_dict.pop('network_mode', None)
  186. if not network_mode:
  187. if self.networks.use_networking:
  188. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  189. return NetworkMode(None)
  190. service_name = get_service_name_from_network_mode(network_mode)
  191. if service_name:
  192. return ServiceNetworkMode(self.get_service(service_name))
  193. container_name = get_container_name_from_network_mode(network_mode)
  194. if container_name:
  195. try:
  196. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  197. except APIError:
  198. raise ConfigurationError(
  199. "Service '{name}' uses the network stack of container '{dep}' which "
  200. "does not exist.".format(name=service_dict['name'], dep=container_name))
  201. return NetworkMode(network_mode)
  202. def get_pid_mode(self, service_dict):
  203. pid_mode = service_dict.pop('pid', None)
  204. if not pid_mode:
  205. return PidMode(None)
  206. service_name = get_service_name_from_network_mode(pid_mode)
  207. if service_name:
  208. return ServicePidMode(self.get_service(service_name))
  209. container_name = get_container_name_from_network_mode(pid_mode)
  210. if container_name:
  211. try:
  212. return ContainerPidMode(Container.from_id(self.client, container_name))
  213. except APIError:
  214. raise ConfigurationError(
  215. "Service '{name}' uses the PID namespace of container '{dep}' which "
  216. "does not exist.".format(name=service_dict['name'], dep=container_name)
  217. )
  218. return PidMode(pid_mode)
  219. def start(self, service_names=None, **options):
  220. containers = []
  221. def start_service(service):
  222. service_containers = service.start(quiet=True, **options)
  223. containers.extend(service_containers)
  224. services = self.get_services(service_names)
  225. def get_deps(service):
  226. return {
  227. (self.get_service(dep), config)
  228. for dep, config in service.get_dependency_configs().items()
  229. }
  230. parallel.parallel_execute(
  231. services,
  232. start_service,
  233. operator.attrgetter('name'),
  234. 'Starting',
  235. get_deps,
  236. )
  237. return containers
  238. def stop(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  239. containers = self.containers(service_names, one_off=one_off)
  240. def get_deps(container):
  241. # actually returning inversed dependencies
  242. return {(other, None) for other in containers
  243. if container.service in
  244. self.get_service(other.service).get_dependency_names()}
  245. parallel.parallel_execute(
  246. containers,
  247. self.build_container_operation_with_timeout_func('stop', options),
  248. operator.attrgetter('name'),
  249. 'Stopping',
  250. get_deps,
  251. )
  252. def pause(self, service_names=None, **options):
  253. containers = self.containers(service_names)
  254. parallel.parallel_pause(reversed(containers), options)
  255. return containers
  256. def unpause(self, service_names=None, **options):
  257. containers = self.containers(service_names)
  258. parallel.parallel_unpause(containers, options)
  259. return containers
  260. def kill(self, service_names=None, **options):
  261. parallel.parallel_kill(self.containers(service_names), options)
  262. def remove_stopped(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  263. parallel.parallel_remove(self.containers(
  264. service_names, stopped=True, one_off=one_off
  265. ), options)
  266. def down(
  267. self,
  268. remove_image_type,
  269. include_volumes,
  270. remove_orphans=False,
  271. timeout=None,
  272. ignore_orphans=False):
  273. self.stop(one_off=OneOffFilter.include, timeout=timeout)
  274. if not ignore_orphans:
  275. self.find_orphan_containers(remove_orphans)
  276. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  277. self.networks.remove()
  278. if include_volumes:
  279. self.volumes.remove()
  280. self.remove_images(remove_image_type)
  281. def remove_images(self, remove_image_type):
  282. for service in self.get_services():
  283. service.remove_image(remove_image_type)
  284. def restart(self, service_names=None, **options):
  285. containers = self.containers(service_names, stopped=True)
  286. parallel.parallel_execute(
  287. containers,
  288. self.build_container_operation_with_timeout_func('restart', options),
  289. operator.attrgetter('name'),
  290. 'Restarting',
  291. )
  292. return containers
  293. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False, memory=None,
  294. build_args=None, gzip=False, parallel_build=False):
  295. services = []
  296. for service in self.get_services(service_names):
  297. if service.can_be_built():
  298. services.append(service)
  299. else:
  300. log.info('%s uses an image, skipping' % service.name)
  301. def build_service(service):
  302. service.build(no_cache, pull, force_rm, memory, build_args, gzip)
  303. if parallel_build:
  304. _, errors = parallel.parallel_execute(
  305. services,
  306. build_service,
  307. operator.attrgetter('name'),
  308. 'Building',
  309. limit=5,
  310. )
  311. if len(errors):
  312. combined_errors = '\n'.join([
  313. e.decode('utf-8') if isinstance(e, six.binary_type) else e for e in errors.values()
  314. ])
  315. raise ProjectError(combined_errors)
  316. else:
  317. for service in services:
  318. build_service(service)
  319. def create(
  320. self,
  321. service_names=None,
  322. strategy=ConvergenceStrategy.changed,
  323. do_build=BuildAction.none,
  324. ):
  325. services = self.get_services_without_duplicate(service_names, include_deps=True)
  326. for svc in services:
  327. svc.ensure_image_exists(do_build=do_build)
  328. plans = self._get_convergence_plans(services, strategy)
  329. for service in services:
  330. service.execute_convergence_plan(
  331. plans[service.name],
  332. detached=True,
  333. start=False)
  334. def events(self, service_names=None):
  335. def build_container_event(event, container):
  336. time = datetime.datetime.fromtimestamp(event['time'])
  337. time = time.replace(
  338. microsecond=microseconds_from_time_nano(event['timeNano']))
  339. return {
  340. 'time': time,
  341. 'type': 'container',
  342. 'action': event['status'],
  343. 'id': container.id,
  344. 'service': container.service,
  345. 'attributes': {
  346. 'name': container.name,
  347. 'image': event['from'],
  348. },
  349. 'container': container,
  350. }
  351. service_names = set(service_names or self.service_names)
  352. for event in self.client.events(
  353. filters={'label': self.labels()},
  354. decode=True
  355. ):
  356. # The first part of this condition is a guard against some events
  357. # broadcasted by swarm that don't have a status field.
  358. # See https://github.com/docker/compose/issues/3316
  359. if 'status' not in event or event['status'] in IMAGE_EVENTS:
  360. # We don't receive any image events because labels aren't applied
  361. # to images
  362. continue
  363. # TODO: get labels from the API v1.22 , see github issue 2618
  364. try:
  365. # this can fail if the container has been removed
  366. container = Container.from_id(self.client, event['id'])
  367. except APIError:
  368. continue
  369. if container.service not in service_names:
  370. continue
  371. yield build_container_event(event, container)
  372. def up(self,
  373. service_names=None,
  374. start_deps=True,
  375. strategy=ConvergenceStrategy.changed,
  376. do_build=BuildAction.none,
  377. timeout=None,
  378. detached=False,
  379. remove_orphans=False,
  380. ignore_orphans=False,
  381. scale_override=None,
  382. rescale=True,
  383. start=True,
  384. always_recreate_deps=False,
  385. reset_container_image=False,
  386. renew_anonymous_volumes=False,
  387. silent=False,
  388. ):
  389. self.initialize()
  390. if not ignore_orphans:
  391. self.find_orphan_containers(remove_orphans)
  392. if scale_override is None:
  393. scale_override = {}
  394. services = self.get_services_without_duplicate(
  395. service_names,
  396. include_deps=start_deps)
  397. for svc in services:
  398. svc.ensure_image_exists(do_build=do_build, silent=silent)
  399. plans = self._get_convergence_plans(
  400. services, strategy, always_recreate_deps=always_recreate_deps)
  401. def do(service):
  402. return service.execute_convergence_plan(
  403. plans[service.name],
  404. timeout=timeout,
  405. detached=detached,
  406. scale_override=scale_override.get(service.name),
  407. rescale=rescale,
  408. start=start,
  409. reset_container_image=reset_container_image,
  410. renew_anonymous_volumes=renew_anonymous_volumes,
  411. )
  412. def get_deps(service):
  413. return {
  414. (self.get_service(dep), config)
  415. for dep, config in service.get_dependency_configs().items()
  416. }
  417. results, errors = parallel.parallel_execute(
  418. services,
  419. do,
  420. operator.attrgetter('name'),
  421. None,
  422. get_deps,
  423. )
  424. if errors:
  425. raise ProjectError(
  426. 'Encountered errors while bringing up the project.'
  427. )
  428. return [
  429. container
  430. for svc_containers in results
  431. if svc_containers is not None
  432. for container in svc_containers
  433. ]
  434. def initialize(self):
  435. self.networks.initialize()
  436. self.volumes.initialize()
  437. def _get_convergence_plans(self, services, strategy, always_recreate_deps=False):
  438. plans = {}
  439. for service in services:
  440. updated_dependencies = [
  441. name
  442. for name in service.get_dependency_names()
  443. if name in plans and
  444. plans[name].action in ('recreate', 'create')
  445. ]
  446. if updated_dependencies and strategy.allows_recreate:
  447. log.debug('%s has upstream changes (%s)',
  448. service.name,
  449. ", ".join(updated_dependencies))
  450. containers_stopped = any(
  451. service.containers(stopped=True, filters={'status': ['created', 'exited']}))
  452. has_links = any(c.get('HostConfig.Links') for c in service.containers())
  453. if always_recreate_deps or containers_stopped or not has_links:
  454. plan = service.convergence_plan(ConvergenceStrategy.always)
  455. else:
  456. plan = service.convergence_plan(strategy)
  457. else:
  458. plan = service.convergence_plan(strategy)
  459. plans[service.name] = plan
  460. return plans
  461. def pull(self, service_names=None, ignore_pull_failures=False, parallel_pull=False, silent=False,
  462. include_deps=False):
  463. services = self.get_services(service_names, include_deps)
  464. msg = not silent and 'Pulling' or None
  465. if parallel_pull:
  466. def pull_service(service):
  467. strm = service.pull(ignore_pull_failures, True, stream=True)
  468. if strm is None: # Attempting to pull service with no `image` key is a no-op
  469. return
  470. writer = parallel.get_stream_writer()
  471. for event in strm:
  472. if 'status' not in event:
  473. continue
  474. status = event['status'].lower()
  475. if 'progressDetail' in event:
  476. detail = event['progressDetail']
  477. if 'current' in detail and 'total' in detail:
  478. percentage = float(detail['current']) / float(detail['total'])
  479. status = '{} ({:.1%})'.format(status, percentage)
  480. writer.write(
  481. msg, service.name, truncate_string(status), lambda s: s
  482. )
  483. _, errors = parallel.parallel_execute(
  484. services,
  485. pull_service,
  486. operator.attrgetter('name'),
  487. msg,
  488. limit=5,
  489. )
  490. if len(errors):
  491. combined_errors = '\n'.join([
  492. e.decode('utf-8') if isinstance(e, six.binary_type) else e for e in errors.values()
  493. ])
  494. raise ProjectError(combined_errors)
  495. else:
  496. for service in services:
  497. service.pull(ignore_pull_failures, silent=silent)
  498. def push(self, service_names=None, ignore_push_failures=False):
  499. for service in self.get_services(service_names, include_deps=False):
  500. service.push(ignore_push_failures)
  501. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  502. ctnrs = list(filter(None, [
  503. Container.from_ps(self.client, container)
  504. for container in self.client.containers(
  505. all=stopped,
  506. filters={'label': self.labels(one_off=one_off)})])
  507. )
  508. if ctnrs:
  509. return ctnrs
  510. return list(filter(lambda c: c.has_legacy_proj_name(self.name), filter(None, [
  511. Container.from_ps(self.client, container)
  512. for container in self.client.containers(
  513. all=stopped,
  514. filters={'label': self.labels(one_off=one_off, legacy=True)})])
  515. ))
  516. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  517. if service_names:
  518. self.validate_service_names(service_names)
  519. else:
  520. service_names = self.service_names
  521. containers = self._labeled_containers(stopped, one_off)
  522. def matches_service_names(container):
  523. return container.labels.get(LABEL_SERVICE) in service_names
  524. return [c for c in containers if matches_service_names(c)]
  525. def find_orphan_containers(self, remove_orphans):
  526. def _find():
  527. containers = self._labeled_containers()
  528. for ctnr in containers:
  529. service_name = ctnr.labels.get(LABEL_SERVICE)
  530. if service_name not in self.service_names:
  531. yield ctnr
  532. orphans = list(_find())
  533. if not orphans:
  534. return
  535. if remove_orphans:
  536. for ctnr in orphans:
  537. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  538. ctnr.kill()
  539. ctnr.remove(force=True)
  540. else:
  541. log.warning(
  542. 'Found orphan containers ({0}) for this project. If '
  543. 'you removed or renamed this service in your compose '
  544. 'file, you can run this command with the '
  545. '--remove-orphans flag to clean it up.'.format(
  546. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  547. )
  548. )
  549. def _inject_deps(self, acc, service):
  550. dep_names = service.get_dependency_names()
  551. if len(dep_names) > 0:
  552. dep_services = self.get_services(
  553. service_names=list(set(dep_names)),
  554. include_deps=True
  555. )
  556. else:
  557. dep_services = []
  558. dep_services.append(service)
  559. return acc + dep_services
  560. def build_container_operation_with_timeout_func(self, operation, options):
  561. def container_operation_with_timeout(container):
  562. if options.get('timeout') is None:
  563. service = self.get_service(container.service)
  564. options['timeout'] = service.stop_timeout(None)
  565. return getattr(container, operation)(**options)
  566. return container_operation_with_timeout
  567. def get_volumes_from(project, service_dict):
  568. volumes_from = service_dict.pop('volumes_from', None)
  569. if not volumes_from:
  570. return []
  571. def build_volume_from(spec):
  572. if spec.type == 'service':
  573. try:
  574. return spec._replace(source=project.get_service(spec.source))
  575. except NoSuchService:
  576. pass
  577. if spec.type == 'container':
  578. try:
  579. container = Container.from_id(project.client, spec.source)
  580. return spec._replace(source=container)
  581. except APIError:
  582. pass
  583. raise ConfigurationError(
  584. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  585. "of a service or container.".format(
  586. service_dict['name'],
  587. spec.source))
  588. return [build_volume_from(vf) for vf in volumes_from]
  589. def get_secrets(service, service_secrets, secret_defs):
  590. secrets = []
  591. for secret in service_secrets:
  592. secret_def = secret_defs.get(secret.source)
  593. if not secret_def:
  594. raise ConfigurationError(
  595. "Service \"{service}\" uses an undefined secret \"{secret}\" "
  596. .format(service=service, secret=secret.source))
  597. if secret_def.get('external'):
  598. log.warn("Service \"{service}\" uses secret \"{secret}\" which is external. "
  599. "External secrets are not available to containers created by "
  600. "docker-compose.".format(service=service, secret=secret.source))
  601. continue
  602. if secret.uid or secret.gid or secret.mode:
  603. log.warn(
  604. "Service \"{service}\" uses secret \"{secret}\" with uid, "
  605. "gid, or mode. These fields are not supported by this "
  606. "implementation of the Compose file".format(
  607. service=service, secret=secret.source
  608. )
  609. )
  610. secrets.append({'secret': secret, 'file': secret_def.get('file')})
  611. return secrets
  612. class NoSuchService(Exception):
  613. def __init__(self, name):
  614. if isinstance(name, six.binary_type):
  615. name = name.decode('utf-8')
  616. self.name = name
  617. self.msg = "No such service: %s" % self.name
  618. def __str__(self):
  619. return self.msg
  620. class ProjectError(Exception):
  621. def __init__(self, msg):
  622. self.msg = msg