service.py 22 KB

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