project.py 25 KB

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