project.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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):
  210. self.stop()
  211. self.remove_stopped(v=include_volumes)
  212. self.networks.remove()
  213. if include_volumes:
  214. self.volumes.remove()
  215. self.remove_images(remove_image_type)
  216. def remove_images(self, remove_image_type):
  217. for service in self.get_services():
  218. service.remove_image(remove_image_type)
  219. def restart(self, service_names=None, **options):
  220. containers = self.containers(service_names, stopped=True)
  221. parallel.parallel_restart(containers, options)
  222. return containers
  223. def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
  224. for service in self.get_services(service_names):
  225. if service.can_be_built():
  226. service.build(no_cache, pull, force_rm)
  227. else:
  228. log.info('%s uses an image, skipping' % service.name)
  229. def create(
  230. self,
  231. service_names=None,
  232. strategy=ConvergenceStrategy.changed,
  233. do_build=BuildAction.none,
  234. ):
  235. services = self.get_services_without_duplicate(service_names, include_deps=True)
  236. plans = self._get_convergence_plans(services, strategy)
  237. for service in services:
  238. service.execute_convergence_plan(
  239. plans[service.name],
  240. do_build,
  241. detached=True,
  242. start=False)
  243. def events(self):
  244. def build_container_event(event, container):
  245. time = datetime.datetime.fromtimestamp(event['time'])
  246. time = time.replace(
  247. microsecond=microseconds_from_time_nano(event['timeNano']))
  248. return {
  249. 'time': time,
  250. 'type': 'container',
  251. 'action': event['status'],
  252. 'id': container.id,
  253. 'service': container.service,
  254. 'attributes': {
  255. 'name': container.name,
  256. 'image': event['from'],
  257. },
  258. 'container': container,
  259. }
  260. service_names = set(self.service_names)
  261. for event in self.client.events(
  262. filters={'label': self.labels()},
  263. decode=True
  264. ):
  265. if event['status'] in IMAGE_EVENTS:
  266. # We don't receive any image events because labels aren't applied
  267. # to images
  268. continue
  269. # TODO: get labels from the API v1.22 , see github issue 2618
  270. # TODO: this can fail if the conatiner is removed, wrap in try/except
  271. container = Container.from_id(self.client, event['id'])
  272. if container.service not in service_names:
  273. continue
  274. yield build_container_event(event, container)
  275. def up(self,
  276. service_names=None,
  277. start_deps=True,
  278. strategy=ConvergenceStrategy.changed,
  279. do_build=BuildAction.none,
  280. timeout=DEFAULT_TIMEOUT,
  281. detached=False):
  282. self.initialize()
  283. services = self.get_services_without_duplicate(
  284. service_names,
  285. include_deps=start_deps)
  286. plans = self._get_convergence_plans(services, strategy)
  287. for svc in services:
  288. svc.ensure_image_exists(do_build=do_build)
  289. def do(service):
  290. return service.execute_convergence_plan(
  291. plans[service.name],
  292. do_build=do_build,
  293. timeout=timeout,
  294. detached=detached
  295. )
  296. def get_deps(service):
  297. return {self.get_service(dep) for dep in service.get_dependency_names()}
  298. results = parallel.parallel_execute(
  299. services,
  300. do,
  301. operator.attrgetter('name'),
  302. None,
  303. get_deps
  304. )
  305. return [
  306. container
  307. for svc_containers in results
  308. if svc_containers is not None
  309. for container in svc_containers
  310. ]
  311. def initialize(self):
  312. self.networks.initialize()
  313. self.volumes.initialize()
  314. def _get_convergence_plans(self, services, strategy):
  315. plans = {}
  316. for service in services:
  317. updated_dependencies = [
  318. name
  319. for name in service.get_dependency_names()
  320. if name in plans and
  321. plans[name].action in ('recreate', 'create')
  322. ]
  323. if updated_dependencies and strategy.allows_recreate:
  324. log.debug('%s has upstream changes (%s)',
  325. service.name,
  326. ", ".join(updated_dependencies))
  327. plan = service.convergence_plan(ConvergenceStrategy.always)
  328. else:
  329. plan = service.convergence_plan(strategy)
  330. plans[service.name] = plan
  331. return plans
  332. def pull(self, service_names=None, ignore_pull_failures=False):
  333. for service in self.get_services(service_names, include_deps=False):
  334. service.pull(ignore_pull_failures)
  335. def containers(self, service_names=None, stopped=False, one_off=False):
  336. if service_names:
  337. self.validate_service_names(service_names)
  338. else:
  339. service_names = self.service_names
  340. containers = list(filter(None, [
  341. Container.from_ps(self.client, container)
  342. for container in self.client.containers(
  343. all=stopped,
  344. filters={'label': self.labels(one_off=one_off)})]))
  345. def matches_service_names(container):
  346. return container.labels.get(LABEL_SERVICE) in service_names
  347. return [c for c in containers if matches_service_names(c)]
  348. def _inject_deps(self, acc, service):
  349. dep_names = service.get_dependency_names()
  350. if len(dep_names) > 0:
  351. dep_services = self.get_services(
  352. service_names=list(set(dep_names)),
  353. include_deps=True
  354. )
  355. else:
  356. dep_services = []
  357. dep_services.append(service)
  358. return acc + dep_services
  359. def get_volumes_from(project, service_dict):
  360. volumes_from = service_dict.pop('volumes_from', None)
  361. if not volumes_from:
  362. return []
  363. def build_volume_from(spec):
  364. if spec.type == 'service':
  365. try:
  366. return spec._replace(source=project.get_service(spec.source))
  367. except NoSuchService:
  368. pass
  369. if spec.type == 'container':
  370. try:
  371. container = Container.from_id(project.client, spec.source)
  372. return spec._replace(source=container)
  373. except APIError:
  374. pass
  375. raise ConfigurationError(
  376. "Service \"{}\" mounts volumes from \"{}\", which is not the name "
  377. "of a service or container.".format(
  378. service_dict['name'],
  379. spec.source))
  380. return [build_volume_from(vf) for vf in volumes_from]
  381. class NoSuchService(Exception):
  382. def __init__(self, name):
  383. self.name = name
  384. self.msg = "No such service: %s" % self.name
  385. def __str__(self):
  386. return self.msg