1
0

service.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. from .container import Container
  9. from .progress_stream import stream_output, StreamOutputError
  10. log = logging.getLogger(__name__)
  11. DOCKER_CONFIG_KEYS = ['image', 'command', 'hostname', 'domainname', 'user', 'detach', 'stdin_open', 'tty', 'mem_limit', 'ports', 'environment', 'dns', 'volumes', 'entrypoint', 'privileged', 'volumes_from', 'net', 'working_dir']
  12. DOCKER_CONFIG_HINTS = {
  13. 'link' : 'links',
  14. 'port' : 'ports',
  15. 'privilege' : 'privileged',
  16. 'priviliged': 'privileged',
  17. 'privilige' : 'privileged',
  18. 'volume' : 'volumes',
  19. 'workdir' : 'working_dir',
  20. }
  21. VALID_NAME_CHARS = '[a-zA-Z0-9]'
  22. class BuildError(Exception):
  23. def __init__(self, service, reason):
  24. self.service = service
  25. self.reason = reason
  26. class CannotBeScaledError(Exception):
  27. pass
  28. class ConfigError(ValueError):
  29. pass
  30. class Service(object):
  31. def __init__(self, name, client=None, project='default', links=None, volumes_from=None, **options):
  32. if not re.match('^%s+$' % VALID_NAME_CHARS, name):
  33. raise ConfigError('Invalid service name "%s" - only %s are allowed' % (name, VALID_NAME_CHARS))
  34. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  35. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  36. if 'image' in options and 'build' in options:
  37. 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)
  38. supported_options = DOCKER_CONFIG_KEYS + ['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.volumes_from = volumes_from or []
  50. self.options = options
  51. def containers(self, stopped=False, one_off=False):
  52. l = []
  53. for container in self.client.containers(all=stopped):
  54. name = get_container_name(container)
  55. if not name or not is_valid_name(name, one_off):
  56. continue
  57. project, name, number = parse_name(name)
  58. if project == self.project and name == self.name:
  59. l.append(Container.from_ps(self.client, container))
  60. return l
  61. def start(self, **options):
  62. for c in self.containers(stopped=True):
  63. self.start_container_if_stopped(c, **options)
  64. def stop(self, **options):
  65. for c in self.containers():
  66. log.info("Stopping %s..." % c.name)
  67. c.stop(**options)
  68. def kill(self, **options):
  69. for c in self.containers():
  70. log.info("Killing %s..." % c.name)
  71. c.kill(**options)
  72. def scale(self, desired_num):
  73. """
  74. Adjusts the number of containers to the specified number and ensures they are running.
  75. - creates containers until there are at least `desired_num`
  76. - stops containers until there are at most `desired_num` running
  77. - starts containers until there are at least `desired_num` running
  78. - removes all stopped containers
  79. """
  80. if not self.can_be_scaled():
  81. raise CannotBeScaledError()
  82. # Create enough containers
  83. containers = self.containers(stopped=True)
  84. while len(containers) < desired_num:
  85. containers.append(self.create_container())
  86. running_containers = []
  87. stopped_containers = []
  88. for c in containers:
  89. if c.is_running:
  90. running_containers.append(c)
  91. else:
  92. stopped_containers.append(c)
  93. running_containers.sort(key=lambda c: c.number)
  94. stopped_containers.sort(key=lambda c: c.number)
  95. # Stop containers
  96. while len(running_containers) > desired_num:
  97. c = running_containers.pop()
  98. log.info("Stopping %s..." % c.name)
  99. c.stop(timeout=1)
  100. stopped_containers.append(c)
  101. # Start containers
  102. while len(running_containers) < desired_num:
  103. c = stopped_containers.pop(0)
  104. log.info("Starting %s..." % c.name)
  105. self.start_container(c)
  106. running_containers.append(c)
  107. self.remove_stopped()
  108. def remove_stopped(self, **options):
  109. for c in self.containers(stopped=True):
  110. if not c.is_running:
  111. log.info("Removing %s..." % c.name)
  112. c.remove(**options)
  113. def create_container(self, one_off=False, **override_options):
  114. """
  115. Create a container for this service. If the image doesn't exist, attempt to pull
  116. it.
  117. """
  118. container_options = self._get_container_create_options(override_options, one_off=one_off)
  119. try:
  120. return Container.create(self.client, **container_options)
  121. except APIError as e:
  122. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  123. log.info('Pulling image %s...' % container_options['image'])
  124. output = self.client.pull(container_options['image'], stream=True)
  125. stream_output(output, sys.stdout)
  126. return Container.create(self.client, **container_options)
  127. raise
  128. def recreate_containers(self, **override_options):
  129. """
  130. If a container for this service doesn't exist, create and start one. If there are
  131. any, stop them, create+start new ones, and remove the old containers.
  132. """
  133. containers = self.containers(stopped=True)
  134. if len(containers) == 0:
  135. log.info("Creating %s..." % self.next_container_name())
  136. container = self.create_container(**override_options)
  137. self.start_container(container)
  138. return [(None, container)]
  139. else:
  140. tuples = []
  141. for c in containers:
  142. log.info("Recreating %s..." % c.name)
  143. tuples.append(self.recreate_container(c, **override_options))
  144. return tuples
  145. def recreate_container(self, container, **override_options):
  146. try:
  147. container.stop()
  148. except APIError as e:
  149. if (e.response.status_code == 500
  150. and e.explanation
  151. and 'no such process' in str(e.explanation)):
  152. pass
  153. else:
  154. raise
  155. intermediate_container = Container.create(
  156. self.client,
  157. image=container.image,
  158. entrypoint=['echo'],
  159. command=[],
  160. )
  161. intermediate_container.start(volumes_from=container.id)
  162. intermediate_container.wait()
  163. container.remove()
  164. options = dict(override_options)
  165. new_container = self.create_container(**options)
  166. self.start_container(new_container, intermediate_container=intermediate_container)
  167. intermediate_container.remove()
  168. return (intermediate_container, new_container)
  169. def start_container_if_stopped(self, container, **options):
  170. if container.is_running:
  171. return container
  172. else:
  173. log.info("Starting %s..." % container.name)
  174. return self.start_container(container, **options)
  175. def start_container(self, container=None, intermediate_container=None, **override_options):
  176. if container is None:
  177. container = self.create_container(**override_options)
  178. options = self.options.copy()
  179. options.update(override_options)
  180. port_bindings = {}
  181. if options.get('ports', None) is not None:
  182. for port in options['ports']:
  183. internal_port, external_port = split_port(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. net = options.get('net', 'bridge')
  196. dns = options.get('dns', None)
  197. container.start(
  198. links=self._get_links(link_to_self=override_options.get('one_off', False)),
  199. port_bindings=port_bindings,
  200. binds=volume_bindings,
  201. volumes_from=self._get_volumes_from(intermediate_container),
  202. privileged=privileged,
  203. network_mode=net,
  204. dns=dns,
  205. )
  206. return container
  207. def start_or_create_containers(self):
  208. containers = self.containers(stopped=True)
  209. if len(containers) == 0:
  210. log.info("Creating %s..." % self.next_container_name())
  211. new_container = self.create_container()
  212. return [self.start_container(new_container)]
  213. else:
  214. return [self.start_container_if_stopped(c) for c in containers]
  215. def get_linked_names(self):
  216. return [s.name for (s, _) in self.links]
  217. def next_container_name(self, one_off=False):
  218. bits = [self.project, self.name]
  219. if one_off:
  220. bits.append('run')
  221. return '_'.join(bits + [str(self.next_container_number(one_off=one_off))])
  222. def next_container_number(self, one_off=False):
  223. numbers = [parse_name(c.name)[2] for c in self.containers(stopped=True, one_off=one_off)]
  224. if len(numbers) == 0:
  225. return 1
  226. else:
  227. return max(numbers) + 1
  228. def _get_links(self, link_to_self):
  229. links = []
  230. for service, link_name in self.links:
  231. for container in service.containers():
  232. links.append((container.name, link_name or service.name))
  233. links.append((container.name, container.name))
  234. links.append((container.name, container.name_without_project))
  235. if link_to_self:
  236. for container in self.containers():
  237. links.append((container.name, self.name))
  238. links.append((container.name, container.name))
  239. links.append((container.name, container.name_without_project))
  240. return links
  241. def _get_volumes_from(self, intermediate_container=None):
  242. volumes_from = []
  243. for v in self.volumes_from:
  244. if isinstance(v, Service):
  245. for container in v.containers(stopped=True):
  246. volumes_from.append(container.id)
  247. elif isinstance(v, Container):
  248. volumes_from.append(v.id)
  249. if intermediate_container:
  250. volumes_from.append(intermediate_container.id)
  251. return volumes_from
  252. def _get_container_create_options(self, override_options, one_off=False):
  253. container_options = dict((k, self.options[k]) for k in DOCKER_CONFIG_KEYS if k in self.options)
  254. container_options.update(override_options)
  255. container_options['name'] = self.next_container_name(one_off)
  256. # If a qualified hostname was given, split it into an
  257. # unqualified hostname and a domainname unless domainname
  258. # was also given explicitly. This matches the behavior of
  259. # the official Docker CLI in that scenario.
  260. if ('hostname' in container_options
  261. and 'domainname' not in container_options
  262. and '.' in container_options['hostname']):
  263. parts = container_options['hostname'].partition('.')
  264. container_options['hostname'] = parts[0]
  265. container_options['domainname'] = parts[2]
  266. if 'ports' in container_options or 'expose' in self.options:
  267. ports = []
  268. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  269. for port in all_ports:
  270. port = str(port)
  271. if ':' in port:
  272. port = port.split(':')[-1]
  273. if '/' in port:
  274. port = tuple(port.split('/'))
  275. ports.append(port)
  276. container_options['ports'] = ports
  277. if 'volumes' in container_options:
  278. container_options['volumes'] = dict((split_volume(v)[1], {}) for v in container_options['volumes'])
  279. if 'environment' in container_options:
  280. if isinstance(container_options['environment'], list):
  281. container_options['environment'] = dict(split_env(e) for e in container_options['environment'])
  282. container_options['environment'] = dict(resolve_env(k, v) for k, v in container_options['environment'].iteritems())
  283. if self.can_be_built():
  284. if len(self.client.images(name=self._build_tag_name())) == 0:
  285. self.build()
  286. container_options['image'] = self._build_tag_name()
  287. # Delete options which are only used when starting
  288. for key in ['privileged', 'net', 'dns']:
  289. if key in container_options:
  290. del container_options[key]
  291. return container_options
  292. def build(self, no_cache=False):
  293. log.info('Building %s...' % self.name)
  294. build_output = self.client.build(
  295. self.options['build'],
  296. tag=self._build_tag_name(),
  297. stream=True,
  298. rm=True,
  299. nocache=no_cache,
  300. )
  301. try:
  302. all_events = stream_output(build_output, sys.stdout)
  303. except StreamOutputError, e:
  304. raise BuildError(self, unicode(e))
  305. image_id = None
  306. for event in all_events:
  307. if 'stream' in event:
  308. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  309. if match:
  310. image_id = match.group(1)
  311. if image_id is None:
  312. raise BuildError(self)
  313. return image_id
  314. def can_be_built(self):
  315. return 'build' in self.options
  316. def _build_tag_name(self):
  317. """
  318. The tag to give to images built for this service.
  319. """
  320. return '%s_%s' % (self.project, self.name)
  321. def can_be_scaled(self):
  322. for port in self.options.get('ports', []):
  323. if ':' in str(port):
  324. return False
  325. return True
  326. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  327. def is_valid_name(name, one_off=False):
  328. match = NAME_RE.match(name)
  329. if match is None:
  330. return False
  331. if one_off:
  332. return match.group(3) == 'run_'
  333. else:
  334. return match.group(3) is None
  335. def parse_name(name, one_off=False):
  336. match = NAME_RE.match(name)
  337. (project, service_name, _, suffix) = match.groups()
  338. return (project, service_name, int(suffix))
  339. def get_container_name(container):
  340. if not container.get('Name') and not container.get('Names'):
  341. return None
  342. # inspect
  343. if 'Name' in container:
  344. return container['Name']
  345. # ps
  346. for name in container['Names']:
  347. if len(name.split('/')) == 2:
  348. return name[1:]
  349. def split_volume(v):
  350. """
  351. If v is of the format EXTERNAL:INTERNAL, returns (EXTERNAL, INTERNAL).
  352. If v is of the format INTERNAL, returns (None, INTERNAL).
  353. """
  354. if ':' in v:
  355. return v.split(':', 1)
  356. else:
  357. return (None, v)
  358. def split_port(port):
  359. port = str(port)
  360. external_ip = None
  361. if ':' in port:
  362. external_port, internal_port = port.rsplit(':', 1)
  363. if ':' in external_port:
  364. external_ip, external_port = external_port.split(':', 1)
  365. else:
  366. external_port, internal_port = (None, port)
  367. if external_ip:
  368. if external_port:
  369. external_port = (external_ip, external_port)
  370. else:
  371. external_port = (external_ip,)
  372. return internal_port, external_port
  373. def split_env(env):
  374. if '=' in env:
  375. return env.split('=', 1)
  376. else:
  377. return env, None
  378. def resolve_env(key, val):
  379. if val is not None:
  380. return key, val
  381. elif key in os.environ:
  382. return key, os.environ[key]
  383. else:
  384. return key, ''