service.py 15 KB

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