project.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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. parallel_limit=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. parallel.GlobalLimit.set_global_limit(value=parallel_limit)
  63. def labels(self, one_off=OneOffFilter.exclude):
  64. labels = ['{0}={1}'.format(LABEL_PROJECT, self.name)]
  65. OneOffFilter.update_labels(one_off, labels)
  66. return labels
  67. @classmethod
  68. def from_config(cls, name, config_data, client, global_parallel_limit=None):
  69. """
  70. Construct a Project from a config.Config object.
  71. """
  72. use_networking = (config_data.version and config_data.version != V1)
  73. networks = build_networks(name, config_data, client)
  74. project_networks = ProjectNetworks.from_services(
  75. config_data.services,
  76. networks,
  77. use_networking)
  78. volumes = ProjectVolumes.from_config(name, config_data, client)
  79. project = cls(name, [], client, project_networks, volumes, config_data.version,
  80. parallel_limit=global_parallel_limit)
  81. for service_dict in config_data.services:
  82. service_dict = dict(service_dict)
  83. if use_networking:
  84. service_networks = get_networks(service_dict, networks)
  85. else:
  86. service_networks = {}
  87. service_dict.pop('networks', None)
  88. links = project.get_links(service_dict)
  89. network_mode = project.get_network_mode(
  90. service_dict, list(service_networks.keys())
  91. )
  92. pid_mode = project.get_pid_mode(service_dict)
  93. volumes_from = get_volumes_from(project, service_dict)
  94. if config_data.version != V1:
  95. service_dict['volumes'] = [
  96. volumes.namespace_spec(volume_spec)
  97. for volume_spec in service_dict.get('volumes', [])
  98. ]
  99. secrets = get_secrets(
  100. service_dict['name'],
  101. service_dict.pop('secrets', None) or [],
  102. config_data.secrets)
  103. project.services.append(
  104. Service(
  105. service_dict.pop('name'),
  106. client=client,
  107. project=name,
  108. use_networking=use_networking,
  109. networks=service_networks,
  110. links=links,
  111. network_mode=network_mode,
  112. volumes_from=volumes_from,
  113. secrets=secrets,
  114. pid_mode=pid_mode,
  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(self, remove_image_type, include_volumes, remove_orphans=False, timeout=None):
  278. self.stop(one_off=OneOffFilter.include, timeout=timeout)
  279. self.find_orphan_containers(remove_orphans)
  280. self.remove_stopped(v=include_volumes, one_off=OneOffFilter.include)
  281. self.networks.remove()
  282. if include_volumes:
  283. self.volumes.remove()
  284. self.remove_images(remove_image_type)
  285. def remove_images(self, remove_image_type):
  286. for service in self.get_services():
  287. service.remove_image(remove_image_type)
  288. def restart(self, service_names=None, **options):
  289. containers = self.containers(service_names, stopped=True)
  290. parallel.parallel_execute(
  291. containers,
  292. self.build_container_operation_with_timeout_func('restart', options),
  293. operator.attrgetter('name'),
  294. 'Restarting',
  295. )
  296. return containers
  297. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False, memory=None,
  298. build_args=None):
  299. for service in self.get_services(service_names):
  300. if service.can_be_built():
  301. service.build(no_cache, pull, force_rm, memory, build_args)
  302. else:
  303. log.info('%s uses an image, skipping' % service.name)
  304. def create(
  305. self,
  306. service_names=None,
  307. strategy=ConvergenceStrategy.changed,
  308. do_build=BuildAction.none,
  309. ):
  310. services = self.get_services_without_duplicate(service_names, include_deps=True)
  311. for svc in services:
  312. svc.ensure_image_exists(do_build=do_build)
  313. plans = self._get_convergence_plans(services, strategy)
  314. for service in services:
  315. service.execute_convergence_plan(
  316. plans[service.name],
  317. detached=True,
  318. start=False)
  319. def events(self, service_names=None):
  320. def build_container_event(event, container):
  321. time = datetime.datetime.fromtimestamp(event['time'])
  322. time = time.replace(
  323. microsecond=microseconds_from_time_nano(event['timeNano']))
  324. return {
  325. 'time': time,
  326. 'type': 'container',
  327. 'action': event['status'],
  328. 'id': container.id,
  329. 'service': container.service,
  330. 'attributes': {
  331. 'name': container.name,
  332. 'image': event['from'],
  333. },
  334. 'container': container,
  335. }
  336. service_names = set(service_names or self.service_names)
  337. for event in self.client.events(
  338. filters={'label': self.labels()},
  339. decode=True
  340. ):
  341. # The first part of this condition is a guard against some events
  342. # broadcasted by swarm that don't have a status field.
  343. # See https://github.com/docker/compose/issues/3316
  344. if 'status' not in event or event['status'] in IMAGE_EVENTS:
  345. # We don't receive any image events because labels aren't applied
  346. # to images
  347. continue
  348. # TODO: get labels from the API v1.22 , see github issue 2618
  349. try:
  350. # this can fail if the container has been removed
  351. container = Container.from_id(self.client, event['id'])
  352. except APIError:
  353. continue
  354. if container.service not in service_names:
  355. continue
  356. yield build_container_event(event, container)
  357. def up(self,
  358. service_names=None,
  359. start_deps=True,
  360. strategy=ConvergenceStrategy.changed,
  361. do_build=BuildAction.none,
  362. timeout=None,
  363. detached=False,
  364. remove_orphans=False,
  365. scale_override=None,
  366. rescale=True,
  367. start=True):
  368. warn_for_swarm_mode(self.client)
  369. self.initialize()
  370. self.find_orphan_containers(remove_orphans)
  371. if scale_override is None:
  372. scale_override = {}
  373. services = self.get_services_without_duplicate(
  374. service_names,
  375. include_deps=start_deps)
  376. for svc in services:
  377. svc.ensure_image_exists(do_build=do_build)
  378. plans = self._get_convergence_plans(services, strategy)
  379. scaled_services = self.get_scaled_services(services, scale_override)
  380. def do(service):
  381. return service.execute_convergence_plan(
  382. plans[service.name],
  383. timeout=timeout,
  384. detached=detached,
  385. scale_override=scale_override.get(service.name),
  386. rescale=rescale,
  387. start=start,
  388. project_services=scaled_services
  389. )
  390. def get_deps(service):
  391. return {
  392. (self.get_service(dep), config)
  393. for dep, config in service.get_dependency_configs().items()
  394. }
  395. results, errors = parallel.parallel_execute(
  396. services,
  397. do,
  398. operator.attrgetter('name'),
  399. None,
  400. get_deps,
  401. )
  402. if errors:
  403. raise ProjectError(
  404. 'Encountered errors while bringing up the project.'
  405. )
  406. return [
  407. container
  408. for svc_containers in results
  409. if svc_containers is not None
  410. for container in svc_containers
  411. ]
  412. def initialize(self):
  413. self.networks.initialize()
  414. self.volumes.initialize()
  415. def _get_convergence_plans(self, services, strategy):
  416. plans = {}
  417. for service in services:
  418. updated_dependencies = [
  419. name
  420. for name in service.get_dependency_names()
  421. if name in plans and
  422. plans[name].action in ('recreate', 'create')
  423. ]
  424. if updated_dependencies and strategy.allows_recreate:
  425. log.debug('%s has upstream changes (%s)',
  426. service.name,
  427. ", ".join(updated_dependencies))
  428. plan = service.convergence_plan(ConvergenceStrategy.always)
  429. else:
  430. plan = service.convergence_plan(strategy)
  431. plans[service.name] = plan
  432. return plans
  433. def pull(self, service_names=None, ignore_pull_failures=False, parallel_pull=False, silent=False):
  434. services = self.get_services(service_names, include_deps=False)
  435. if parallel_pull:
  436. def pull_service(service):
  437. service.pull(ignore_pull_failures, True)
  438. _, errors = parallel.parallel_execute(
  439. services,
  440. pull_service,
  441. operator.attrgetter('name'),
  442. 'Pulling',
  443. limit=5,
  444. )
  445. if len(errors):
  446. raise ProjectError(b"\n".join(errors.values()))
  447. else:
  448. for service in services:
  449. service.pull(ignore_pull_failures, silent=silent)
  450. def push(self, service_names=None, ignore_push_failures=False):
  451. for service in self.get_services(service_names, include_deps=False):
  452. service.push(ignore_push_failures)
  453. def _labeled_containers(self, stopped=False, one_off=OneOffFilter.exclude):
  454. return list(filter(None, [
  455. Container.from_ps(self.client, container)
  456. for container in self.client.containers(
  457. all=stopped,
  458. filters={'label': self.labels(one_off=one_off)})])
  459. )
  460. def containers(self, service_names=None, stopped=False, one_off=OneOffFilter.exclude):
  461. if service_names:
  462. self.validate_service_names(service_names)
  463. else:
  464. service_names = self.service_names
  465. containers = self._labeled_containers(stopped, one_off)
  466. def matches_service_names(container):
  467. return container.labels.get(LABEL_SERVICE) in service_names
  468. return [c for c in containers if matches_service_names(c)]
  469. def find_orphan_containers(self, remove_orphans):
  470. def _find():
  471. containers = self._labeled_containers()
  472. for ctnr in containers:
  473. service_name = ctnr.labels.get(LABEL_SERVICE)
  474. if service_name not in self.service_names:
  475. yield ctnr
  476. orphans = list(_find())
  477. if not orphans:
  478. return
  479. if remove_orphans:
  480. for ctnr in orphans:
  481. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  482. ctnr.kill()
  483. ctnr.remove(force=True)
  484. else:
  485. log.warning(
  486. 'Found orphan containers ({0}) for this project. If '
  487. 'you removed or renamed this service in your compose '
  488. 'file, you can run this command with the '
  489. '--remove-orphans flag to clean it up.'.format(
  490. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  491. )
  492. )
  493. def _inject_deps(self, acc, service):
  494. dep_names = service.get_dependency_names()
  495. if len(dep_names) > 0:
  496. dep_services = self.get_services(
  497. service_names=list(set(dep_names)),
  498. include_deps=True
  499. )
  500. else:
  501. dep_services = []
  502. dep_services.append(service)
  503. return acc + dep_services
  504. def build_container_operation_with_timeout_func(self, operation, options):
  505. def container_operation_with_timeout(container):
  506. if options.get('timeout') is None:
  507. service = self.get_service(container.service)
  508. options['timeout'] = service.stop_timeout(None)
  509. return getattr(container, operation)(**options)
  510. return container_operation_with_timeout
  511. def get_volumes_from(project, service_dict):
  512. volumes_from = service_dict.pop('volumes_from', None)
  513. if not volumes_from:
  514. return []
  515. def build_volume_from(spec):
  516. if spec.type == 'service':
  517. try:
  518. return spec._replace(source=project.get_service(spec.source))
  519. except NoSuchService:
  520. pass
  521. if spec.type == 'container':
  522. try:
  523. container = Container.from_id(project.client, spec.source)
  524. return spec._replace(source=container)
  525. except APIError:
  526. pass
  527. raise ConfigurationError(
  528. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  529. "of a service or container.".format(
  530. service_dict['name'],
  531. spec.source))
  532. return [build_volume_from(vf) for vf in volumes_from]
  533. def get_secrets(service, service_secrets, secret_defs):
  534. secrets = []
  535. for secret in service_secrets:
  536. secret_def = secret_defs.get(secret.source)
  537. if not secret_def:
  538. raise ConfigurationError(
  539. "Service \"{service}\" uses an undefined secret \"{secret}\" "
  540. .format(service=service, secret=secret.source))
  541. if secret_def.get('external'):
  542. log.warn("Service \"{service}\" uses secret \"{secret}\" which is external. "
  543. "External secrets are not available to containers created by "
  544. "docker-compose.".format(service=service, secret=secret.source))
  545. continue
  546. if secret.uid or secret.gid or secret.mode:
  547. log.warn(
  548. "Service \"{service}\" uses secret \"{secret}\" with uid, "
  549. "gid, or mode. These fields are not supported by this "
  550. "implementation of the Compose file".format(
  551. service=service, secret=secret.source
  552. )
  553. )
  554. secrets.append({'secret': secret, 'file': secret_def.get('file')})
  555. return secrets
  556. def warn_for_swarm_mode(client):
  557. info = client.info()
  558. if info.get('Swarm', {}).get('LocalNodeState') == 'active':
  559. if info.get('ServerVersion', '').startswith('ucp'):
  560. # UCP does multi-node scheduling with traditional Compose files.
  561. return
  562. log.warn(
  563. "The Docker Engine you're using is running in swarm mode.\n\n"
  564. "Compose does not use swarm mode to deploy services to multiple nodes in a swarm. "
  565. "All containers will be scheduled on the current node.\n\n"
  566. "To deploy your application across the swarm, "
  567. "use `docker stack deploy`.\n"
  568. )
  569. class NoSuchService(Exception):
  570. def __init__(self, name):
  571. self.name = name
  572. self.msg = "No such service: %s" % self.name
  573. def __str__(self):
  574. return self.msg
  575. class ProjectError(Exception):
  576. def __init__(self, msg):
  577. self.msg = msg