project.py 17 KB

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