project.py 24 KB

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