service.py 21 KB

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