project.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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 ServiceName
  32. from .service import ServiceNetworkMode
  33. from .service import ServicePidMode
  34. from .utils import microseconds_from_time_nano
  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_scaled_services(self, services, scale_override):
  169. """
  170. Returns a list of this project's services as scaled ServiceName objects.
  171. services: a list of Service objects
  172. scale_override: a dict with the scale to apply to each service (k: service_name, v: scale)
  173. """
  174. service_names = []
  175. for service in services:
  176. if service.name in scale_override:
  177. scale = scale_override[service.name]
  178. else:
  179. scale = service.scale_num
  180. for i in range(1, scale + 1):
  181. service_names.append(ServiceName(self.name, service.name, i))
  182. return service_names
  183. def get_links(self, service_dict):
  184. links = []
  185. if 'links' in service_dict:
  186. for link in service_dict.get('links', []):
  187. if ':' in link:
  188. service_name, link_name = link.split(':', 1)
  189. else:
  190. service_name, link_name = link, None
  191. try:
  192. links.append((self.get_service(service_name), link_name))
  193. except NoSuchService:
  194. raise ConfigurationError(
  195. 'Service "%s" has a link to service "%s" which does not '
  196. 'exist.' % (service_dict['name'], service_name))
  197. del service_dict['links']
  198. return links
  199. def get_network_mode(self, service_dict, networks):
  200. network_mode = service_dict.pop('network_mode', None)
  201. if not network_mode:
  202. if self.networks.use_networking:
  203. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  204. return NetworkMode(None)
  205. service_name = get_service_name_from_network_mode(network_mode)
  206. if service_name:
  207. return ServiceNetworkMode(self.get_service(service_name))
  208. container_name = get_container_name_from_network_mode(network_mode)
  209. if container_name:
  210. try:
  211. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  212. except APIError:
  213. raise ConfigurationError(
  214. "Service '{name}' uses the network stack of container '{dep}' which "
  215. "does not exist.".format(name=service_dict['name'], dep=container_name))
  216. return NetworkMode(network_mode)
  217. def get_pid_mode(self, service_dict):
  218. pid_mode = service_dict.pop('pid', None)
  219. if not pid_mode:
  220. return PidMode(None)
  221. service_name = get_service_name_from_network_mode(pid_mode)
  222. if service_name:
  223. return ServicePidMode(self.get_service(service_name))
  224. container_name = get_container_name_from_network_mode(pid_mode)
  225. if container_name:
  226. try:
  227. return ContainerPidMode(Container.from_id(self.client, container_name))
  228. except APIError:
  229. raise ConfigurationError(
  230. "Service '{name}' uses the PID namespace of container '{dep}' which "
  231. "does not exist.".format(name=service_dict['name'], dep=container_name)
  232. )
  233. return PidMode(pid_mode)
  234. def start(self, service_names=None, **options):
  235. containers = []
  236. def start_service(service):
  237. service_containers = service.start(quiet=True, **options)
  238. containers.extend(service_containers)
  239. services = self.get_services(service_names)
  240. def get_deps(service):
  241. return {
  242. (self.get_service(dep), config)
  243. for dep, config in service.get_dependency_configs().items()
  244. }
  245. parallel.parallel_execute(
  246. services,
  247. start_service,
  248. operator.attrgetter('name'),
  249. 'Starting',
  250. get_deps,
  251. )
  252. return containers
  253. def stop(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  254. containers = self.containers(service_names, one_off=one_off)
  255. def get_deps(container):
  256. # actually returning inversed dependencies
  257. return {(other, None) for other in containers
  258. if container.service in
  259. self.get_service(other.service).get_dependency_names()}
  260. parallel.parallel_execute(
  261. containers,
  262. self.build_container_operation_with_timeout_func('stop', options),
  263. operator.attrgetter('name'),
  264. 'Stopping',
  265. get_deps,
  266. )
  267. def pause(self, service_names=None, **options):
  268. containers = self.containers(service_names)
  269. parallel.parallel_pause(reversed(containers), options)
  270. return containers
  271. def unpause(self, service_names=None, **options):
  272. containers = self.containers(service_names)
  273. parallel.parallel_unpause(containers, options)
  274. return containers
  275. def kill(self, service_names=None, **options):
  276. parallel.parallel_kill(self.containers(service_names), options)
  277. def remove_stopped(self, service_names=None, one_off=OneOffFilter.exclude, **options):
  278. parallel.parallel_remove(self.containers(
  279. service_names, stopped=True, one_off=one_off
  280. ), options)
  281. def down(
  282. self,
  283. remove_image_type,
  284. include_volumes,
  285. remove_orphans=False,
  286. timeout=None,
  287. ignore_orphans=False):
  288. self.stop(one_off=OneOffFilter.include, timeout=timeout)
  289. if not ignore_orphans:
  290. self.find_orphan_containers(remove_orphans)
  291. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  292. self.networks.remove()
  293. if include_volumes:
  294. self.volumes.remove()
  295. self.remove_images(remove_image_type)
  296. def remove_images(self, remove_image_type):
  297. for service in self.get_services():
  298. service.remove_image(remove_image_type)
  299. def restart(self, service_names=None, **options):
  300. containers = self.containers(service_names, stopped=True)
  301. parallel.parallel_execute(
  302. containers,
  303. self.build_container_operation_with_timeout_func('restart', options),
  304. operator.attrgetter('name'),
  305. 'Restarting',
  306. )
  307. return containers
  308. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False, memory=None,
  309. build_args=None, gzip=False, parallel_build=False):
  310. services = []
  311. for service in self.get_services(service_names):
  312. if service.can_be_built():
  313. services.append(service)
  314. else:
  315. log.info('%s uses an image, skipping' % service.name)
  316. def build_service(service):
  317. service.build(no_cache, pull, force_rm, memory, build_args, gzip)
  318. if parallel_build:
  319. _, errors = parallel.parallel_execute(
  320. services,
  321. build_service,
  322. operator.attrgetter('name'),
  323. 'Building',
  324. limit=5,
  325. )
  326. if len(errors):
  327. combined_errors = '\n'.join([
  328. e.decode('utf-8') if isinstance(e, six.binary_type) else e for e in errors.values()
  329. ])
  330. raise ProjectError(combined_errors)
  331. else:
  332. for service in services:
  333. build_service(service)
  334. def create(
  335. self,
  336. service_names=None,
  337. strategy=ConvergenceStrategy.changed,
  338. do_build=BuildAction.none,
  339. ):
  340. services = self.get_services_without_duplicate(service_names, include_deps=True)
  341. for svc in services:
  342. svc.ensure_image_exists(do_build=do_build)
  343. plans = self._get_convergence_plans(services, strategy)
  344. for service in services:
  345. service.execute_convergence_plan(
  346. plans[service.name],
  347. detached=True,
  348. start=False)
  349. def events(self, service_names=None):
  350. def build_container_event(event, container):
  351. time = datetime.datetime.fromtimestamp(event['time'])
  352. time = time.replace(
  353. microsecond=microseconds_from_time_nano(event['timeNano']))
  354. return {
  355. 'time': time,
  356. 'type': 'container',
  357. 'action': event['status'],
  358. 'id': container.id,
  359. 'service': container.service,
  360. 'attributes': {
  361. 'name': container.name,
  362. 'image': event['from'],
  363. },
  364. 'container': container,
  365. }
  366. service_names = set(service_names or self.service_names)
  367. for event in self.client.events(
  368. filters={'label': self.labels()},
  369. decode=True
  370. ):
  371. # The first part of this condition is a guard against some events
  372. # broadcasted by swarm that don't have a status field.
  373. # See https://github.com/docker/compose/issues/3316
  374. if 'status' not in event or event['status'] in IMAGE_EVENTS:
  375. # We don't receive any image events because labels aren't applied
  376. # to images
  377. continue
  378. # TODO: get labels from the API v1.22 , see github issue 2618
  379. try:
  380. # this can fail if the container has been removed
  381. container = Container.from_id(self.client, event['id'])
  382. except APIError:
  383. continue
  384. if container.service not in service_names:
  385. continue
  386. yield build_container_event(event, container)
  387. def up(self,
  388. service_names=None,
  389. start_deps=True,
  390. strategy=ConvergenceStrategy.changed,
  391. do_build=BuildAction.none,
  392. timeout=None,
  393. detached=False,
  394. remove_orphans=False,
  395. ignore_orphans=False,
  396. scale_override=None,
  397. rescale=True,
  398. start=True,
  399. always_recreate_deps=False,
  400. reset_container_image=False,
  401. renew_anonymous_volumes=False,
  402. silent=False,
  403. ):
  404. self.initialize()
  405. if not ignore_orphans:
  406. self.find_orphan_containers(remove_orphans)
  407. if scale_override is None:
  408. scale_override = {}
  409. services = self.get_services_without_duplicate(
  410. service_names,
  411. include_deps=start_deps)
  412. for svc in services:
  413. svc.ensure_image_exists(do_build=do_build, silent=silent)
  414. plans = self._get_convergence_plans(
  415. services, strategy, always_recreate_deps=always_recreate_deps)
  416. scaled_services = self.get_scaled_services(services, scale_override)
  417. def do(service):
  418. return service.execute_convergence_plan(
  419. plans[service.name],
  420. timeout=timeout,
  421. detached=detached,
  422. scale_override=scale_override.get(service.name),
  423. rescale=rescale,
  424. start=start,
  425. project_services=scaled_services,
  426. reset_container_image=reset_container_image,
  427. renew_anonymous_volumes=renew_anonymous_volumes,
  428. )
  429. def get_deps(service):
  430. return {
  431. (self.get_service(dep), config)
  432. for dep, config in service.get_dependency_configs().items()
  433. }
  434. results, errors = parallel.parallel_execute(
  435. services,
  436. do,
  437. operator.attrgetter('name'),
  438. None,
  439. get_deps,
  440. )
  441. if errors:
  442. raise ProjectError(
  443. 'Encountered errors while bringing up the project.'
  444. )
  445. return [
  446. container
  447. for svc_containers in results
  448. if svc_containers is not None
  449. for container in svc_containers
  450. ]
  451. def initialize(self):
  452. self.networks.initialize()
  453. self.volumes.initialize()
  454. def _get_convergence_plans(self, services, strategy, always_recreate_deps=False):
  455. plans = {}
  456. for service in services:
  457. updated_dependencies = [
  458. name
  459. for name in service.get_dependency_names()
  460. if name in plans and
  461. plans[name].action in ('recreate', 'create')
  462. ]
  463. if updated_dependencies and strategy.allows_recreate:
  464. log.debug('%s has upstream changes (%s)',
  465. service.name,
  466. ", ".join(updated_dependencies))
  467. containers_stopped = any(
  468. service.containers(stopped=True, filters={'status': ['created', 'exited']}))
  469. has_links = any(c.get('HostConfig.Links') for c in service.containers())
  470. if always_recreate_deps or containers_stopped or not has_links:
  471. plan = service.convergence_plan(ConvergenceStrategy.always)
  472. else:
  473. plan = service.convergence_plan(strategy)
  474. else:
  475. plan = service.convergence_plan(strategy)
  476. plans[service.name] = plan
  477. return plans
  478. def pull(self, service_names=None, ignore_pull_failures=False, parallel_pull=False, silent=False,
  479. include_deps=False):
  480. services = self.get_services(service_names, include_deps)
  481. if parallel_pull:
  482. def pull_service(service):
  483. service.pull(ignore_pull_failures, True)
  484. _, errors = parallel.parallel_execute(
  485. services,
  486. pull_service,
  487. operator.attrgetter('name'),
  488. not silent and 'Pulling' or None,
  489. limit=5,
  490. )
  491. if len(errors):
  492. combined_errors = '\n'.join([
  493. e.decode('utf-8') if isinstance(e, six.binary_type) else e for e in errors.values()
  494. ])
  495. raise ProjectError(combined_errors)
  496. else:
  497. for service in services:
  498. service.pull(ignore_pull_failures, silent=silent)
  499. def push(self, service_names=None, ignore_push_failures=False):
  500. for service in self.get_services(service_names, include_deps=False):
  501. service.push(ignore_push_failures)
  502. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  503. ctnrs = list(filter(None, [
  504. Container.from_ps(self.client, container)
  505. for container in self.client.containers(
  506. all=stopped,
  507. filters={'label': self.labels(one_off=one_off)})])
  508. )
  509. if ctnrs:
  510. return ctnrs
  511. return list(filter(lambda c: c.has_legacy_proj_name(self.name), filter(None, [
  512. Container.from_ps(self.client, container)
  513. for container in self.client.containers(
  514. all=stopped,
  515. filters={'label': self.labels(one_off=one_off, legacy=True)})])
  516. ))
  517. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  518. if service_names:
  519. self.validate_service_names(service_names)
  520. else:
  521. service_names = self.service_names
  522. containers = self._labeled_containers(stopped, one_off)
  523. def matches_service_names(container):
  524. return container.labels.get(LABEL_SERVICE) in service_names
  525. return [c for c in containers if matches_service_names(c)]
  526. def find_orphan_containers(self, remove_orphans):
  527. def _find():
  528. containers = self._labeled_containers()
  529. for ctnr in containers:
  530. service_name = ctnr.labels.get(LABEL_SERVICE)
  531. if service_name not in self.service_names:
  532. yield ctnr
  533. orphans = list(_find())
  534. if not orphans:
  535. return
  536. if remove_orphans:
  537. for ctnr in orphans:
  538. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  539. ctnr.kill()
  540. ctnr.remove(force=True)
  541. else:
  542. log.warning(
  543. 'Found orphan containers ({0}) for this project. If '
  544. 'you removed or renamed this service in your compose '
  545. 'file, you can run this command with the '
  546. '--remove-orphans flag to clean it up.'.format(
  547. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  548. )
  549. )
  550. def _inject_deps(self, acc, service):
  551. dep_names = service.get_dependency_names()
  552. if len(dep_names) > 0:
  553. dep_services = self.get_services(
  554. service_names=list(set(dep_names)),
  555. include_deps=True
  556. )
  557. else:
  558. dep_services = []
  559. dep_services.append(service)
  560. return acc + dep_services
  561. def build_container_operation_with_timeout_func(self, operation, options):
  562. def container_operation_with_timeout(container):
  563. if options.get('timeout') is None:
  564. service = self.get_service(container.service)
  565. options['timeout'] = service.stop_timeout(None)
  566. return getattr(container, operation)(**options)
  567. return container_operation_with_timeout
  568. def get_volumes_from(project, service_dict):
  569. volumes_from = service_dict.pop('volumes_from', None)
  570. if not volumes_from:
  571. return []
  572. def build_volume_from(spec):
  573. if spec.type == 'service':
  574. try:
  575. return spec._replace(source=project.get_service(spec.source))
  576. except NoSuchService:
  577. pass
  578. if spec.type == 'container':
  579. try:
  580. container = Container.from_id(project.client, spec.source)
  581. return spec._replace(source=container)
  582. except APIError:
  583. pass
  584. raise ConfigurationError(
  585. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  586. "of a service or container.".format(
  587. service_dict['name'],
  588. spec.source))
  589. return [build_volume_from(vf) for vf in volumes_from]
  590. def get_secrets(service, service_secrets, secret_defs):
  591. secrets = []
  592. for secret in service_secrets:
  593. secret_def = secret_defs.get(secret.source)
  594. if not secret_def:
  595. raise ConfigurationError(
  596. "Service \"{service}\" uses an undefined secret \"{secret}\" "
  597. .format(service=service, secret=secret.source))
  598. if secret_def.get('external'):
  599. log.warn("Service \"{service}\" uses secret \"{secret}\" which is external. "
  600. "External secrets are not available to containers created by "
  601. "docker-compose.".format(service=service, secret=secret.source))
  602. continue
  603. if secret.uid or secret.gid or secret.mode:
  604. log.warn(
  605. "Service \"{service}\" uses secret \"{secret}\" with uid, "
  606. "gid, or mode. These fields are not supported by this "
  607. "implementation of the Compose file".format(
  608. service=service, secret=secret.source
  609. )
  610. )
  611. secrets.append({'secret': secret, 'file': secret_def.get('file')})
  612. return secrets
  613. class NoSuchService(Exception):
  614. def __init__(self, name):
  615. if isinstance(name, six.binary_type):
  616. name = name.decode('utf-8')
  617. self.name = name
  618. self.msg = "No such service: %s" % self.name
  619. def __str__(self):
  620. return self.msg
  621. class ProjectError(Exception):
  622. def __init__(self, msg):
  623. self.msg = msg