service.py 22 KB

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