service.py 23 KB

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