service.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from collections import namedtuple
  4. import logging
  5. import re
  6. import os
  7. from operator import attrgetter
  8. import sys
  9. from docker.errors import APIError
  10. from .container import Container
  11. from .progress_stream import stream_output, StreamOutputError
  12. log = logging.getLogger(__name__)
  13. DOCKER_CONFIG_KEYS = [
  14. 'cap_add',
  15. 'cap_drop',
  16. '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:`fig.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
  204. there are any, stop them, create+start new ones, and remove the old
  205. containers.
  206. """
  207. containers = self.containers(stopped=True)
  208. if not containers:
  209. log.info("Creating %s..." % self._next_container_name(containers))
  210. container = self.create_container(
  211. insecure_registry=insecure_registry,
  212. do_build=do_build,
  213. **override_options)
  214. self.start_container(container)
  215. return [container]
  216. else:
  217. return [
  218. self.recreate_container(
  219. container,
  220. insecure_registry=insecure_registry,
  221. **override_options)
  222. for container in containers
  223. ]
  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. log.info("Recreating %s..." % container.name)
  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 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, 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 get_container_name(container):
  451. if not container.get('Name') and not container.get('Names'):
  452. return None
  453. # inspect
  454. if 'Name' in container:
  455. return container['Name']
  456. # ps
  457. for name in container['Names']:
  458. if len(name.split('/')) == 2:
  459. return name[1:]
  460. def parse_restart_spec(restart_config):
  461. if not restart_config:
  462. return None
  463. parts = restart_config.split(':')
  464. if len(parts) > 2:
  465. raise ConfigError("Restart %s has incorrect format, should be "
  466. "mode[:max_retry]" % restart_config)
  467. if len(parts) == 2:
  468. name, max_retry_count = parts
  469. else:
  470. name, = parts
  471. max_retry_count = 0
  472. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  473. def parse_volume_spec(volume_config):
  474. parts = volume_config.split(':')
  475. if len(parts) > 3:
  476. raise ConfigError("Volume %s has incorrect format, should be "
  477. "external:internal[:mode]" % volume_config)
  478. if len(parts) == 1:
  479. return VolumeSpec(None, parts[0], 'rw')
  480. if len(parts) == 2:
  481. parts.append('rw')
  482. external, internal, mode = parts
  483. if mode not in ('rw', 'ro'):
  484. raise ConfigError("Volume %s has invalid mode (%s), should be "
  485. "one of: rw, ro." % (volume_config, mode))
  486. return VolumeSpec(external, internal, mode)
  487. def parse_repository_tag(s):
  488. if ":" not in s:
  489. return s, ""
  490. repo, tag = s.rsplit(":", 1)
  491. if "/" in tag:
  492. return s, ""
  493. return repo, tag
  494. def build_volume_binding(volume_spec):
  495. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  496. external = os.path.expanduser(volume_spec.external)
  497. return os.path.abspath(os.path.expandvars(external)), internal
  498. def build_port_bindings(ports):
  499. port_bindings = {}
  500. for port in ports:
  501. internal_port, external = split_port(port)
  502. if internal_port in port_bindings:
  503. port_bindings[internal_port].append(external)
  504. else:
  505. port_bindings[internal_port] = [external]
  506. return port_bindings
  507. def split_port(port):
  508. parts = str(port).split(':')
  509. if not 1 <= len(parts) <= 3:
  510. raise ConfigError('Invalid port "%s", should be '
  511. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  512. if len(parts) == 1:
  513. internal_port, = parts
  514. return internal_port, None
  515. if len(parts) == 2:
  516. external_port, internal_port = parts
  517. return internal_port, external_port
  518. external_ip, external_port, internal_port = parts
  519. return internal_port, (external_ip, external_port or None)
  520. def merge_environment(options):
  521. env = {}
  522. if 'env_file' in options:
  523. if isinstance(options['env_file'], list):
  524. for f in options['env_file']:
  525. env.update(env_vars_from_file(f))
  526. else:
  527. env.update(env_vars_from_file(options['env_file']))
  528. if 'environment' in options:
  529. if isinstance(options['environment'], list):
  530. env.update(dict(split_env(e) for e in options['environment']))
  531. else:
  532. env.update(options['environment'])
  533. return dict(resolve_env(k, v) for k, v in env.iteritems())
  534. def split_env(env):
  535. if '=' in env:
  536. return env.split('=', 1)
  537. else:
  538. return env, None
  539. def resolve_env(key, val):
  540. if val is not None:
  541. return key, val
  542. elif key in os.environ:
  543. return key, os.environ[key]
  544. else:
  545. return key, ''
  546. def env_vars_from_file(filename):
  547. """
  548. Read in a line delimited file of environment variables.
  549. """
  550. env = {}
  551. for line in open(filename, 'r'):
  552. line = line.strip()
  553. if line and not line.startswith('#'):
  554. k, v = split_env(line)
  555. env[k] = v
  556. return env