project.py 25 KB

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