service.py 16 KB

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