service.py 15 KB

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