service.py 16 KB

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