service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from collections import namedtuple
  4. from .packages.docker.errors import APIError
  5. import logging
  6. import re
  7. import os
  8. import sys
  9. from .container import Container
  10. from .progress_stream import stream_output, StreamOutputError
  11. log = logging.getLogger(__name__)
  12. DOCKER_CONFIG_KEYS = ['image', 'command', 'hostname', 'domainname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'entrypoint', 'privileged', 'volumes_from', 'net', 'working_dir']
  13. DOCKER_CONFIG_HINTS = {
  14. 'link' : 'links',
  15. 'port' : 'ports',
  16. 'privilege' : 'privileged',
  17. 'priviliged': 'privileged',
  18. 'privilige' : 'privileged',
  19. 'volume' : 'volumes',
  20. 'workdir' : 'working_dir',
  21. }
  22. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  23. class BuildError(Exception):
  24. def __init__(self, service, reason):
  25. self.service = service
  26. self.reason = reason
  27. class CannotBeScaledError(Exception):
  28. pass
  29. class ConfigError(ValueError):
  30. pass
  31. VolumeSpec = namedtuple('VolumeSpec', 'external internal mode')
  32. class Service(object):
  33. def __init__(self, name, client=None, project='default', links=None, volumes_from=None, **options):
  34. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  35. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  36. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  37. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  38. if 'image' in options and 'build' in options:
  39. raise ConfigError('Service %s has both an image and build path specified. A service can either be built to image or use an existing image, not both.' % name)
  40. supported_options = DOCKER_CONFIG_KEYS + ['build', 'expose']
  41. for k in options:
  42. if k not in supported_options:
  43. msg = "Unsupported config option for %s service: '%s'" % (name, k)
  44. if k in DOCKER_CONFIG_HINTS:
  45. msg += " (did you mean '%s'?)" % DOCKER_CONFIG_HINTS[k]
  46. raise ConfigError(msg)
  47. self.name = name
  48. self.client = client
  49. self.project = project
  50. self.links = links or []
  51. self.volumes_from = volumes_from or []
  52. self.options = options
  53. def containers(self, stopped=False, one_off=False):
  54. return [Container.from_ps(self.client, container)
  55. for container in self.client.containers(all=stopped)
  56. if self.has_container(container, one_off=one_off)]
  57. def has_container(self, container, one_off=False):
  58. """Return True if `container` was created to fulfill this service."""
  59. name = get_container_name(container)
  60. if not name or not is_valid_name(name, one_off):
  61. return False
  62. project, name, number = parse_name(name)
  63. return project == self.project and name == self.name
  64. def start(self, **options):
  65. for c in self.containers(stopped=True):
  66. self.start_container_if_stopped(c, **options)
  67. def stop(self, **options):
  68. for c in self.containers():
  69. log.info("Stopping %s..." % c.name)
  70. c.stop(**options)
  71. def kill(self, **options):
  72. for c in self.containers():
  73. log.info("Killing %s..." % c.name)
  74. c.kill(**options)
  75. def scale(self, desired_num):
  76. """
  77. Adjusts the number of containers to the specified number and ensures they are running.
  78. - creates containers until there are at least `desired_num`
  79. - stops containers until there are at most `desired_num` running
  80. - starts containers until there are at least `desired_num` running
  81. - removes all stopped containers
  82. """
  83. if not self.can_be_scaled():
  84. raise CannotBeScaledError()
  85. # Create enough containers
  86. containers = self.containers(stopped=True)
  87. while len(containers) < desired_num:
  88. containers.append(self.create_container())
  89. running_containers = []
  90. stopped_containers = []
  91. for c in containers:
  92. if c.is_running:
  93. running_containers.append(c)
  94. else:
  95. stopped_containers.append(c)
  96. running_containers.sort(key=lambda c: c.number)
  97. stopped_containers.sort(key=lambda c: c.number)
  98. # Stop containers
  99. while len(running_containers) > desired_num:
  100. c = running_containers.pop()
  101. log.info("Stopping %s..." % c.name)
  102. c.stop(timeout=1)
  103. stopped_containers.append(c)
  104. # Start containers
  105. while len(running_containers) < desired_num:
  106. c = stopped_containers.pop(0)
  107. log.info("Starting %s..." % c.name)
  108. self.start_container(c)
  109. running_containers.append(c)
  110. self.remove_stopped()
  111. def remove_stopped(self, **options):
  112. for c in self.containers(stopped=True):
  113. if not c.is_running:
  114. log.info("Removing %s..." % c.name)
  115. c.remove(**options)
  116. def create_container(self, one_off=False, **override_options):
  117. """
  118. Create a container for this service. If the image doesn't exist, attempt to pull
  119. it.
  120. """
  121. container_options = self._get_container_create_options(override_options, one_off=one_off)
  122. try:
  123. return Container.create(self.client, **container_options)
  124. except APIError as e:
  125. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  126. log.info('Pulling image %s...' % container_options['image'])
  127. output = self.client.pull(container_options['image'], stream=True)
  128. stream_output(output, sys.stdout)
  129. return Container.create(self.client, **container_options)
  130. raise
  131. def recreate_containers(self, **override_options):
  132. """
  133. If a container for this service doesn't exist, create and start one. If there are
  134. any, stop them, create+start new ones, and remove the old containers.
  135. """
  136. containers = self.containers(stopped=True)
  137. if len(containers) == 0:
  138. log.info("Creating %s..." % self.next_container_name())
  139. container = self.create_container(**override_options)
  140. self.start_container(container)
  141. return [(None, container)]
  142. else:
  143. tuples = []
  144. for c in containers:
  145. log.info("Recreating %s..." % c.name)
  146. tuples.append(self.recreate_container(c, **override_options))
  147. return tuples
  148. def recreate_container(self, container, **override_options):
  149. try:
  150. container.stop()
  151. except APIError as e:
  152. if (e.response.status_code == 500
  153. and e.explanation
  154. and 'no such process' in str(e.explanation)):
  155. pass
  156. else:
  157. raise
  158. intermediate_container = Container.create(
  159. self.client,
  160. image=container.image,
  161. entrypoint=['echo'],
  162. command=[],
  163. )
  164. intermediate_container.start(volumes_from=container.id)
  165. intermediate_container.wait()
  166. container.remove()
  167. options = dict(override_options)
  168. new_container = self.create_container(**options)
  169. self.start_container(new_container, intermediate_container=intermediate_container)
  170. intermediate_container.remove()
  171. return (intermediate_container, new_container)
  172. def start_container_if_stopped(self, container, **options):
  173. if container.is_running:
  174. return container
  175. else:
  176. log.info("Starting %s..." % container.name)
  177. return self.start_container(container, **options)
  178. def start_container(self, container=None, intermediate_container=None, **override_options):
  179. container = container or self.create_container(**override_options)
  180. options = dict(self.options, **override_options)
  181. ports = dict(split_port(port) for port in options.get('ports') or [])
  182. volume_bindings = dict(
  183. build_volume_binding(parse_volume_spec(volume))
  184. for volume in options.get('volumes') or []
  185. if ':' in volume)
  186. privileged = options.get('privileged', False)
  187. net = options.get('net', 'bridge')
  188. dns = options.get('dns', None)
  189. container.start(
  190. links=self._get_links(link_to_self=options.get('one_off', False)),
  191. port_bindings=ports,
  192. binds=volume_bindings,
  193. volumes_from=self._get_volumes_from(intermediate_container),
  194. privileged=privileged,
  195. network_mode=net,
  196. dns=dns,
  197. )
  198. return container
  199. def start_or_create_containers(self):
  200. containers = self.containers(stopped=True)
  201. if not containers:
  202. log.info("Creating %s..." % self.next_container_name())
  203. new_container = self.create_container()
  204. return [self.start_container(new_container)]
  205. else:
  206. return [self.start_container_if_stopped(c) for c in containers]
  207. def get_linked_names(self):
  208. return [s.name for (s, _) in self.links]
  209. def next_container_name(self, one_off=False):
  210. bits = [self.project, self.name]
  211. if one_off:
  212. bits.append('run')
  213. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  214. def next_container_number(self, one_off=False):
  215. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  216. if len(numbers) == 0:
  217. return 1
  218. else:
  219. return max(numbers) + 1
  220. def _get_links(self, link_to_self):
  221. links = []
  222. for service, link_name in self.links:
  223. for container in service.containers():
  224. if link_name:
  225. links.append((container.name, link_name))
  226. links.append((container.name, container.name))
  227. links.append((container.name, container.name_without_project))
  228. if link_to_self:
  229. for container in self.containers():
  230. links.append((container.name, container.name))
  231. links.append((container.name, container.name_without_project))
  232. return links
  233. def _get_volumes_from(self, intermediate_container=None):
  234. volumes_from = []
  235. for v in self.volumes_from:
  236. if isinstance(v, Service):
  237. for container in v.containers(stopped=True):
  238. volumes_from.append(container.id)
  239. elif isinstance(v, Container):
  240. volumes_from.append(v.id)
  241. if intermediate_container:
  242. volumes_from.append(intermediate_container.id)
  243. return volumes_from
  244. def _get_container_create_options(self, override_options, one_off=False):
  245. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  246. container_options.update(override_options)
  247. container_options['name'] = self.next_container_name(one_off)
  248. # If a qualified hostname was given, split it into an
  249. # unqualified hostname and a domainname unless domainname
  250. # was also given explicitly. This matches the behavior of
  251. # the official Docker CLI in that scenario.
  252. if ('hostname' in container_options
  253. and 'domainname' not in container_options
  254. and '.' in container_options['hostname']):
  255. parts = container_options['hostname'].partition('.')
  256. container_options['hostname'] = parts[0]
  257. container_options['domainname'] = parts[2]
  258. if 'ports' in container_options or 'expose' in self.options:
  259. ports = []
  260. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  261. for port in all_ports:
  262. port = str(port)
  263. if ':' in port:
  264. port = port.split(':')[-1]
  265. if '/' in port:
  266. port = tuple(port.split('/'))
  267. ports.append(port)
  268. container_options['ports'] = ports
  269. if 'volumes' in container_options:
  270. container_options['volumes'] = dict(
  271. (parse_volume_spec(v).internal, {})
  272. for v in container_options['volumes'])
  273. if 'environment' in container_options:
  274. if isinstance(container_options['environment'], list):
  275. container_options['environment'] = dict(split_env(e) for e in container_options['environment'])
  276. container_options['environment'] = dict(resolve_env(k, v) for k, v in container_options['environment'].iteritems())
  277. if self.can_be_built():
  278. if len(self.client.images(name=self._build_tag_name())) == 0:
  279. self.build()
  280. container_options['image'] = self._build_tag_name()
  281. # Delete options which are only used when starting
  282. for key in ['privileged', 'net', 'dns']:
  283. if key in container_options:
  284. del container_options[key]
  285. return container_options
  286. def build(self, no_cache=False):
  287. log.info('Building %s...' % self.name)
  288. build_output = self.client.build(
  289. self.options['build'],
  290. tag=self._build_tag_name(),
  291. stream=True,
  292. rm=True,
  293. nocache=no_cache,
  294. )
  295. try:
  296. all_events = stream_output(build_output, sys.stdout)
  297. except StreamOutputError, e:
  298. raise BuildError(self, unicode(e))
  299. image_id = None
  300. for event in all_events:
  301. if 'stream' in event:
  302. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  303. if match:
  304. image_id = match.group(1)
  305. if image_id is None:
  306. raise BuildError(self)
  307. return image_id
  308. def can_be_built(self):
  309. return 'build' in self.options
  310. def _build_tag_name(self):
  311. """
  312. The tag to give to images built for this service.
  313. """
  314. return '%s_%s' % (self.project, self.name)
  315. def can_be_scaled(self):
  316. for port in self.options.get('ports', []):
  317. if ':' in str(port):
  318. return False
  319. return True
  320. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  321. def is_valid_name(name, one_off=False):
  322. match = NAME_RE.match(name)
  323. if match is None:
  324. return False
  325. if one_off:
  326. return match.group(3) == 'run_'
  327. else:
  328. return match.group(3) is None
  329. def parse_name(name, one_off=False):
  330. match = NAME_RE.match(name)
  331. (project, service_name, _, suffix) = match.groups()
  332. return (project, service_name, int(suffix))
  333. def get_container_name(container):
  334. if not container.get('Name') and not container.get('Names'):
  335. return None
  336. # inspect
  337. if 'Name' in container:
  338. return container['Name']
  339. # ps
  340. for name in container['Names']:
  341. if len(name.split('/')) == 2:
  342. return name[1:]
  343. def parse_volume_spec(volume_config):
  344. parts = volume_config.split(':')
  345. if len(parts) > 3:
  346. raise ConfigError("Volume %s has incorrect format, should be "
  347. "external:internal[:mode]" % volume_config)
  348. if len(parts) == 1:
  349. return VolumeSpec(None, parts[0], 'rw')
  350. if len(parts) == 2:
  351. parts.append('rw')
  352. external, internal, mode = parts
  353. if mode not in ('rw', 'ro'):
  354. raise ConfigError("Volume %s has invalid mode (%s), should be "
  355. "one of: rw, ro." % (volume_config, mode))
  356. return VolumeSpec(external, internal, mode)
  357. def build_volume_binding(volume_spec):
  358. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  359. external = os.path.expanduser(volume_spec.external)
  360. return os.path.abspath(os.path.expandvars(external)), internal
  361. def split_port(port):
  362. parts = str(port).split(':')
  363. if not 1 <= len(parts) <= 3:
  364. raise ConfigError('Invalid port "%s", should be '
  365. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  366. if len(parts) == 1:
  367. internal_port, = parts
  368. return internal_port, None
  369. if len(parts) == 2:
  370. external_port, internal_port = parts
  371. return internal_port, external_port
  372. external_ip, external_port, internal_port = parts
  373. return internal_port, (external_ip, external_port or None)
  374. def split_env(env):
  375. if '=' in env:
  376. return env.split('=', 1)
  377. else:
  378. return env, None
  379. def resolve_env(key, val):
  380. if val is not None:
  381. return key, val
  382. elif key in os.environ:
  383. return key, os.environ[key]
  384. else:
  385. return key, ''