service.py 18 KB

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