service.py 17 KB

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