service.py 22 KB

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