project.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. from docker.errors import APIError
  8. from . import parallel
  9. from .config import ConfigurationError
  10. from .config.config import V1
  11. from .config.sort_services import get_container_name_from_network_mode
  12. from .config.sort_services import get_service_name_from_network_mode
  13. from .const import DEFAULT_TIMEOUT
  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 ConvergenceStrategy
  25. from .service import NetworkMode
  26. from .service import Service
  27. from .service import ServiceNetworkMode
  28. from .utils import microseconds_from_time_nano
  29. from .volume import ProjectVolumes
  30. log = logging.getLogger(__name__)
  31. class Project(object):
  32. """
  33. A collection of services.
  34. """
  35. def __init__(self, name, services, client, networks=None, volumes=None):
  36. self.name = name
  37. self.services = services
  38. self.client = client
  39. self.volumes = volumes or ProjectVolumes({})
  40. self.networks = networks or ProjectNetworks({}, False)
  41. def labels(self, one_off=False):
  42. return [
  43. '{0}={1}'.format(LABEL_PROJECT, self.name),
  44. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False"),
  45. ]
  46. @classmethod
  47. def from_config(cls, name, config_data, client):
  48. """
  49. Construct a Project from a config.Config object.
  50. """
  51. use_networking = (config_data.version and config_data.version != V1)
  52. networks = build_networks(name, config_data, client)
  53. project_networks = ProjectNetworks.from_services(
  54. config_data.services,
  55. networks,
  56. use_networking)
  57. volumes = ProjectVolumes.from_config(name, config_data, client)
  58. project = cls(name, [], client, project_networks, volumes)
  59. for service_dict in config_data.services:
  60. service_dict = dict(service_dict)
  61. if use_networking:
  62. service_networks = get_networks(service_dict, networks)
  63. else:
  64. service_networks = {}
  65. service_dict.pop('networks', None)
  66. links = project.get_links(service_dict)
  67. network_mode = project.get_network_mode(
  68. service_dict, list(service_networks.keys())
  69. )
  70. volumes_from = get_volumes_from(project, service_dict)
  71. if config_data.version != V1:
  72. service_dict['volumes'] = [
  73. volumes.namespace_spec(volume_spec)
  74. for volume_spec in service_dict.get('volumes', [])
  75. ]
  76. project.services.append(
  77. Service(
  78. service_dict.pop('name'),
  79. client=client,
  80. project=name,
  81. use_networking=use_networking,
  82. networks=service_networks,
  83. links=links,
  84. network_mode=network_mode,
  85. volumes_from=volumes_from,
  86. **service_dict)
  87. )
  88. return project
  89. @property
  90. def service_names(self):
  91. return [service.name for service in self.services]
  92. def get_service(self, name):
  93. """
  94. Retrieve a service by name. Raises NoSuchService
  95. if the named service does not exist.
  96. """
  97. for service in self.services:
  98. if service.name == name:
  99. return service
  100. raise NoSuchService(name)
  101. def validate_service_names(self, service_names):
  102. """
  103. Validate that the given list of service names only contains valid
  104. services. Raises NoSuchService if one of the names is invalid.
  105. """
  106. valid_names = self.service_names
  107. for name in service_names:
  108. if name not in valid_names:
  109. raise NoSuchService(name)
  110. def get_services(self, service_names=None, include_deps=False):
  111. """
  112. Returns a list of this project's services filtered
  113. by the provided list of names, or all services if service_names is None
  114. or [].
  115. If include_deps is specified, returns a list including the dependencies for
  116. service_names, in order of dependency.
  117. Preserves the original order of self.services where possible,
  118. reordering as needed to resolve dependencies.
  119. Raises NoSuchService if any of the named services do not exist.
  120. """
  121. if service_names is None or len(service_names) == 0:
  122. service_names = self.service_names
  123. unsorted = [self.get_service(name) for name in service_names]
  124. services = [s for s in self.services if s in unsorted]
  125. if include_deps:
  126. services = reduce(self._inject_deps, services, [])
  127. uniques = []
  128. [uniques.append(s) for s in services if s not in uniques]
  129. return uniques
  130. def get_services_without_duplicate(self, service_names=None, include_deps=False):
  131. services = self.get_services(service_names, include_deps)
  132. for service in services:
  133. service.remove_duplicate_containers()
  134. return services
  135. def get_links(self, service_dict):
  136. links = []
  137. if 'links' in service_dict:
  138. for link in service_dict.get('links', []):
  139. if ':' in link:
  140. service_name, link_name = link.split(':', 1)
  141. else:
  142. service_name, link_name = link, None
  143. try:
  144. links.append((self.get_service(service_name), link_name))
  145. except NoSuchService:
  146. raise ConfigurationError(
  147. 'Service "%s" has a link to service "%s" which does not '
  148. 'exist.' % (service_dict['name'], service_name))
  149. del service_dict['links']
  150. return links
  151. def get_network_mode(self, service_dict, networks):
  152. network_mode = service_dict.pop('network_mode', None)
  153. if not network_mode:
  154. if self.networks.use_networking:
  155. return NetworkMode(networks[0]) if networks else NetworkMode('none')
  156. return NetworkMode(None)
  157. service_name = get_service_name_from_network_mode(network_mode)
  158. if service_name:
  159. return ServiceNetworkMode(self.get_service(service_name))
  160. container_name = get_container_name_from_network_mode(network_mode)
  161. if container_name:
  162. try:
  163. return ContainerNetworkMode(Container.from_id(self.client, container_name))
  164. except APIError:
  165. raise ConfigurationError(
  166. "Service '{name}' uses the network stack of container '{dep}' which "
  167. "does not exist.".format(name=service_dict['name'], dep=container_name))
  168. return NetworkMode(network_mode)
  169. def start(self, service_names=None, **options):
  170. containers = []
  171. def start_service(service):
  172. service_containers = service.start(quiet=True, **options)
  173. containers.extend(service_containers)
  174. services = self.get_services(service_names)
  175. def get_deps(service):
  176. return {self.get_service(dep) for dep in service.get_dependency_names()}
  177. parallel.parallel_execute(
  178. services,
  179. start_service,
  180. operator.attrgetter('name'),
  181. 'Starting',
  182. get_deps)
  183. return containers
  184. def stop(self, service_names=None, **options):
  185. containers = self.containers(service_names)
  186. def get_deps(container):
  187. # actually returning inversed dependencies
  188. return {other for other in containers
  189. if container.service in
  190. self.get_service(other.service).get_dependency_names()}
  191. parallel.parallel_execute(
  192. containers,
  193. operator.methodcaller('stop', **options),
  194. operator.attrgetter('name'),
  195. 'Stopping',
  196. get_deps)
  197. def pause(self, service_names=None, **options):
  198. containers = self.containers(service_names)
  199. parallel.parallel_pause(reversed(containers), options)
  200. return containers
  201. def unpause(self, service_names=None, **options):
  202. containers = self.containers(service_names)
  203. parallel.parallel_unpause(containers, options)
  204. return containers
  205. def kill(self, service_names=None, **options):
  206. parallel.parallel_kill(self.containers(service_names), options)
  207. def remove_stopped(self, service_names=None, **options):
  208. parallel.parallel_remove(self.containers(service_names, stopped=True), options)
  209. def down(self, remove_image_type, include_volumes, remove_orphans=False):
  210. self.stop()
  211. self.find_orphan_containers(remove_orphans)
  212. self.remove_stopped(v=include_volumes)
  213. self.networks.remove()
  214. if include_volumes:
  215. self.volumes.remove()
  216. self.remove_images(remove_image_type)
  217. def remove_images(self, remove_image_type):
  218. for service in self.get_services():
  219. service.remove_image(remove_image_type)
  220. def restart(self, service_names=None, **options):
  221. containers = self.containers(service_names, stopped=True)
  222. parallel.parallel_restart(containers, options)
  223. return containers
  224. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
  225. for service in self.get_services(service_names):
  226. if service.can_be_built():
  227. service.build(no_cache, pull, force_rm)
  228. else:
  229. log.info('%s uses an image, skipping' % service.name)
  230. def create(
  231. self,
  232. service_names=None,
  233. strategy=ConvergenceStrategy.changed,
  234. do_build=BuildAction.none,
  235. ):
  236. services = self.get_services_without_duplicate(service_names, include_deps=True)
  237. plans = self._get_convergence_plans(services, strategy)
  238. for service in services:
  239. service.execute_convergence_plan(
  240. plans[service.name],
  241. do_build,
  242. detached=True,
  243. start=False)
  244. def events(self, service_names=None):
  245. def build_container_event(event, container):
  246. time = datetime.datetime.fromtimestamp(event['time'])
  247. time = time.replace(
  248. microsecond=microseconds_from_time_nano(event['timeNano']))
  249. return {
  250. 'time': time,
  251. 'type': 'container',
  252. 'action': event['status'],
  253. 'id': container.id,
  254. 'service': container.service,
  255. 'attributes': {
  256. 'name': container.name,
  257. 'image': event['from'],
  258. },
  259. 'container': container,
  260. }
  261. service_names = set(service_names or self.service_names)
  262. for event in self.client.events(
  263. filters={'label': self.labels()},
  264. decode=True
  265. ):
  266. if event['status'] in IMAGE_EVENTS:
  267. # We don't receive any image events because labels aren't applied
  268. # to images
  269. continue
  270. # TODO: get labels from the API v1.22 , see github issue 2618
  271. try:
  272. # this can fail if the conatiner has been removed
  273. container = Container.from_id(self.client, event['id'])
  274. except APIError:
  275. continue
  276. if container.service not in service_names:
  277. continue
  278. yield build_container_event(event, container)
  279. def up(self,
  280. service_names=None,
  281. start_deps=True,
  282. strategy=ConvergenceStrategy.changed,
  283. do_build=BuildAction.none,
  284. timeout=DEFAULT_TIMEOUT,
  285. detached=False,
  286. remove_orphans=False):
  287. self.initialize()
  288. services = self.get_services_without_duplicate(
  289. service_names,
  290. include_deps=start_deps)
  291. plans = self._get_convergence_plans(services, strategy)
  292. for svc in services:
  293. svc.ensure_image_exists(do_build=do_build)
  294. self.find_orphan_containers(remove_orphans)
  295. def do(service):
  296. return service.execute_convergence_plan(
  297. plans[service.name],
  298. do_build=do_build,
  299. timeout=timeout,
  300. detached=detached
  301. )
  302. def get_deps(service):
  303. return {self.get_service(dep) for dep in service.get_dependency_names()}
  304. results = parallel.parallel_execute(
  305. services,
  306. do,
  307. operator.attrgetter('name'),
  308. None,
  309. get_deps
  310. )
  311. return [
  312. container
  313. for svc_containers in results
  314. if svc_containers is not None
  315. for container in svc_containers
  316. ]
  317. def initialize(self):
  318. self.networks.initialize()
  319. self.volumes.initialize()
  320. def _get_convergence_plans(self, services, strategy):
  321. plans = {}
  322. for service in services:
  323. updated_dependencies = [
  324. name
  325. for name in service.get_dependency_names()
  326. if name in plans and
  327. plans[name].action in ('recreate', 'create')
  328. ]
  329. if updated_dependencies and strategy.allows_recreate:
  330. log.debug('%s has upstream changes (%s)',
  331. service.name,
  332. ", ".join(updated_dependencies))
  333. plan = service.convergence_plan(ConvergenceStrategy.always)
  334. else:
  335. plan = service.convergence_plan(strategy)
  336. plans[service.name] = plan
  337. return plans
  338. def pull(self, service_names=None, ignore_pull_failures=False):
  339. for service in self.get_services(service_names, include_deps=False):
  340. service.pull(ignore_pull_failures)
  341. def _labeled_containers(self, stopped=False, one_off=False):
  342. return list(filter(None, [
  343. Container.from_ps(self.client, container)
  344. for container in self.client.containers(
  345. all=stopped,
  346. filters={'label': self.labels(one_off=one_off)})])
  347. )
  348. def containers(self, service_names=None, stopped=False, one_off=False):
  349. if service_names:
  350. self.validate_service_names(service_names)
  351. else:
  352. service_names = self.service_names
  353. containers = self._labeled_containers(stopped, one_off)
  354. def matches_service_names(container):
  355. return container.labels.get(LABEL_SERVICE) in service_names
  356. return [c for c in containers if matches_service_names(c)]
  357. def find_orphan_containers(self, remove_orphans):
  358. def _find():
  359. containers = self._labeled_containers()
  360. for ctnr in containers:
  361. service_name = ctnr.labels.get(LABEL_SERVICE)
  362. if service_name not in self.service_names:
  363. yield ctnr
  364. orphans = list(_find())
  365. if not orphans:
  366. return
  367. if remove_orphans:
  368. for ctnr in orphans:
  369. log.info('Removing orphan container "{0}"'.format(ctnr.name))
  370. ctnr.kill()
  371. ctnr.remove(force=True)
  372. else:
  373. log.warning(
  374. 'Found orphan containers ({0}) for this project. If '
  375. 'you removed or renamed this service in your compose '
  376. 'file, you can run this command with the '
  377. '--remove-orphans flag to clean it up.'.format(
  378. ', '.join(["{}".format(ctnr.name) for ctnr in orphans])
  379. )
  380. )
  381. def _inject_deps(self, acc, service):
  382. dep_names = service.get_dependency_names()
  383. if len(dep_names) > 0:
  384. dep_services = self.get_services(
  385. service_names=list(set(dep_names)),
  386. include_deps=True
  387. )
  388. else:
  389. dep_services = []
  390. dep_services.append(service)
  391. return acc + dep_services
  392. def get_volumes_from(project, service_dict):
  393. volumes_from = service_dict.pop('volumes_from', None)
  394. if not volumes_from:
  395. return []
  396. def build_volume_from(spec):
  397. if spec.type == 'service':
  398. try:
  399. return spec._replace(source=project.get_service(spec.source))
  400. except NoSuchService:
  401. pass
  402. if spec.type == 'container':
  403. try:
  404. container = Container.from_id(project.client, spec.source)
  405. return spec._replace(source=container)
  406. except APIError:
  407. pass
  408. raise ConfigurationError(
  409. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  410. "of a service or container.".format(
  411. service_dict['name'],
  412. spec.source))
  413. return [build_volume_from(vf) for vf in volumes_from]
  414. class NoSuchService(Exception):
  415. def __init__(self, name):
  416. self.name = name
  417. self.msg = "No such service: %s" % self.name
  418. def __str__(self):
  419. return self.msg