project.py 18 KB

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