service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. self.start_container_if_stopped(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, keep_old=False, **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. elif keep_old:
  139. return [(None, self.start_container_if_stopped(c)) for c in containers]
  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_if_stopped(self, container, **options):
  166. if container.is_running:
  167. return container
  168. else:
  169. log.info("Starting %s..." % container.name)
  170. return self.start_container(container, **options)
  171. def start_container(self, container=None, volumes_from=None, **override_options):
  172. if container is None:
  173. container = self.create_container(**override_options)
  174. options = self.options.copy()
  175. options.update(override_options)
  176. port_bindings = {}
  177. if options.get('ports', None) is not None:
  178. for port in options['ports']:
  179. port = str(port)
  180. if ':' in port:
  181. external_port, internal_port = port.split(':', 1)
  182. else:
  183. external_port, internal_port = (None, port)
  184. port_bindings[internal_port] = external_port
  185. volume_bindings = {}
  186. if options.get('volumes', None) is not None:
  187. for volume in options['volumes']:
  188. if ':' in volume:
  189. external_dir, internal_dir = volume.split(':')
  190. volume_bindings[os.path.abspath(external_dir)] = {
  191. 'bind': internal_dir,
  192. 'ro': False,
  193. }
  194. privileged = options.get('privileged', False)
  195. container.start(
  196. links=self._get_links(link_to_self=override_options.get('one_off', False)),
  197. port_bindings=port_bindings,
  198. binds=volume_bindings,
  199. volumes_from=volumes_from,
  200. privileged=privileged,
  201. )
  202. return container
  203. def get_linked_names(self):
  204. return [s.name for (s, _) in self.links]
  205. def next_container_name(self, one_off=False):
  206. bits = [self.project, self.name]
  207. if one_off:
  208. bits.append('run')
  209. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  210. def next_container_number(self, one_off=False):
  211. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  212. if len(numbers) == 0:
  213. return 1
  214. else:
  215. return max(numbers) + 1
  216. def _get_links(self, link_to_self):
  217. links = []
  218. for service, link_name in self.links:
  219. for container in service.containers():
  220. if link_name:
  221. links.append((container.name, link_name))
  222. links.append((container.name, container.name))
  223. links.append((container.name, container.name_without_project))
  224. if link_to_self:
  225. for container in self.containers():
  226. links.append((container.name, container.name))
  227. links.append((container.name, container.name_without_project))
  228. return links
  229. def _get_container_create_options(self, override_options, one_off=False):
  230. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  231. container_options.update(override_options)
  232. container_options['name'] = self.next_container_name(one_off)
  233. if 'ports' in container_options or 'expose' in self.options:
  234. ports = []
  235. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  236. for port in all_ports:
  237. port = str(port)
  238. if ':' in port:
  239. port = port.split(':')[-1]
  240. if '/' in port:
  241. port = tuple(port.split('/'))
  242. ports.append(port)
  243. container_options['ports'] = ports
  244. if 'volumes' in container_options:
  245. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  246. if self.can_be_built():
  247. if len(self.client.images(name=self._build_tag_name())) == 0:
  248. self.build()
  249. container_options['image'] = self._build_tag_name()
  250. # Priviliged is only required for starting containers, not for creating them
  251. if 'privileged' in container_options:
  252. del container_options['privileged']
  253. return container_options
  254. def build(self):
  255. log.info('Building %s...' % self.name)
  256. build_output = self.client.build(
  257. self.options['build'],
  258. tag=self._build_tag_name(),
  259. stream=True,
  260. rm=True
  261. )
  262. try:
  263. all_events = stream_output(build_output, sys.stdout)
  264. except StreamOutputError, e:
  265. raise BuildError(self, unicode(e))
  266. image_id = None
  267. for event in all_events:
  268. if 'stream' in event:
  269. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  270. if match:
  271. image_id = match.group(1)
  272. if image_id is None:
  273. raise BuildError(self)
  274. return image_id
  275. def can_be_built(self):
  276. return 'build' in self.options
  277. def _build_tag_name(self):
  278. """
  279. The tag to give to images built for this service.
  280. """
  281. return '%s_%s' % (self.project, self.name)
  282. def can_be_scaled(self):
  283. for port in self.options.get('ports', []):
  284. if ':' in str(port):
  285. return False
  286. return True
  287. class StreamOutputError(Exception):
  288. pass
  289. def stream_output(output, stream):
  290. is_terminal = hasattr(stream, 'fileno') and os.isatty(stream.fileno())
  291. all_events = []
  292. lines = {}
  293. diff = 0
  294. for chunk in output:
  295. event = json.loads(chunk)
  296. all_events.append(event)
  297. if 'progress' in event or 'progressDetail' in event:
  298. image_id = event['id']
  299. if image_id in lines:
  300. diff = len(lines) - lines[image_id]
  301. else:
  302. lines[image_id] = len(lines)
  303. stream.write("\n")
  304. diff = 0
  305. if is_terminal:
  306. # move cursor up `diff` rows
  307. stream.write("%c[%dA" % (27, diff))
  308. print_output_event(event, stream, is_terminal)
  309. if 'id' in event and is_terminal:
  310. # move cursor back down
  311. stream.write("%c[%dB" % (27, diff))
  312. stream.flush()
  313. return all_events
  314. def print_output_event(event, stream, is_terminal):
  315. if 'errorDetail' in event:
  316. raise StreamOutputError(event['errorDetail']['message'])
  317. terminator = ''
  318. if is_terminal and 'stream' not in event:
  319. # erase current line
  320. stream.write("%c[2K\r" % 27)
  321. terminator = "\r"
  322. pass
  323. elif 'progressDetail' in event:
  324. return
  325. if 'time' in event:
  326. stream.write("[%s] " % event['time'])
  327. if 'id' in event:
  328. stream.write("%s: " % event['id'])
  329. if 'from' in event:
  330. stream.write("(from %s) " % event['from'])
  331. status = event.get('status', '')
  332. if 'progress' in event:
  333. stream.write("%s %s%s" % (status, event['progress'], terminator))
  334. elif 'progressDetail' in event:
  335. detail = event['progressDetail']
  336. if 'current' in detail:
  337. percentage = float(detail['current']) / float(detail['total']) * 100
  338. stream.write('%s (%.1f%%)%s' % (status, percentage, terminator))
  339. else:
  340. stream.write('%s%s' % (status, terminator))
  341. elif 'stream' in event:
  342. stream.write("%s%s" % (event['stream'], terminator))
  343. else:
  344. stream.write("%s%s\n" % (status, terminator))
  345. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  346. def is_valid_name(name, one_off=False):
  347. match = NAME_RE.match(name)
  348. if match is None:
  349. return False
  350. if one_off:
  351. return match.group(3) == 'run_'
  352. else:
  353. return match.group(3) is None
  354. def parse_name(name, one_off=False):
  355. match = NAME_RE.match(name)
  356. (project, service_name, _, suffix) = match.groups()
  357. return (project, service_name, int(suffix))
  358. def get_container_name(container):
  359. if not container.get('Name') and not container.get('Names'):
  360. return None
  361. # inspect
  362. if 'Name' in container:
  363. return container['Name']
  364. # ps
  365. for name in container['Names']:
  366. if len(name.split('/')) == 2:
  367. return name[1:]
  368. def split_volume(v):
  369. """
  370. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  371. If v is of the format INTERNAL, returns (None, INTERNAL).
  372. """
  373. if ':' in v:
  374. return v.split(':', 1)
  375. else:
  376. return (None, v)