service.py 21 KB

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