project.py 25 KB

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