service.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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_options = dict(self.options, **override_options)
  240. intermediate_container = Container.create(
  241. self.client,
  242. image=container.image,
  243. entrypoint=['/bin/echo'],
  244. command=[],
  245. detach=True,
  246. )
  247. intermediate_container.start(
  248. binds=get_container_data_volumes(
  249. container, intermediate_options.get('volumes')))
  250. intermediate_container.wait()
  251. container.remove()
  252. # TODO: volumes are being passed to both start and create, this is
  253. # probably unnecessary
  254. options = dict(override_options)
  255. new_container = self.create_container(do_build=False, **options)
  256. self.start_container(
  257. new_container,
  258. intermediate_container=intermediate_container)
  259. intermediate_container.remove()
  260. return new_container
  261. def start_container_if_stopped(self, container, **options):
  262. if container.is_running:
  263. return container
  264. else:
  265. log.info("Starting %s..." % container.name)
  266. return self.start_container(container, **options)
  267. def start_container(self, container, intermediate_container=None, **override_options):
  268. options = dict(self.options, **override_options)
  269. port_bindings = build_port_bindings(options.get('ports') or [])
  270. privileged = options.get('privileged', False)
  271. net = options.get('net', 'bridge')
  272. dns = options.get('dns', None)
  273. dns_search = options.get('dns_search', None)
  274. cap_add = options.get('cap_add', None)
  275. cap_drop = options.get('cap_drop', None)
  276. restart = parse_restart_spec(options.get('restart', None))
  277. binds = get_volume_bindings(
  278. options.get('volumes'), intermediate_container)
  279. container.start(
  280. links=self._get_links(link_to_self=options.get('one_off', False)),
  281. port_bindings=port_bindings,
  282. binds=binds,
  283. volumes_from=self._get_volumes_from(),
  284. privileged=privileged,
  285. network_mode=net,
  286. dns=dns,
  287. dns_search=dns_search,
  288. restart_policy=restart,
  289. cap_add=cap_add,
  290. cap_drop=cap_drop,
  291. )
  292. return container
  293. def start_or_create_containers(
  294. self,
  295. insecure_registry=False,
  296. detach=False,
  297. do_build=True):
  298. containers = self.containers(stopped=True)
  299. if not containers:
  300. log.info("Creating %s..." % self._next_container_name(containers))
  301. new_container = self.create_container(
  302. insecure_registry=insecure_registry,
  303. detach=detach,
  304. do_build=do_build,
  305. )
  306. return [self.start_container(new_container)]
  307. else:
  308. return [self.start_container_if_stopped(c) for c in containers]
  309. def get_linked_names(self):
  310. return [s.name for (s, _) in self.links]
  311. def _next_container_name(self, all_containers, one_off=False):
  312. bits = [self.project, self.name]
  313. if one_off:
  314. bits.append('run')
  315. return '_'.join(bits + [str(self._next_container_number(all_containers))])
  316. def _next_container_number(self, all_containers):
  317. numbers = [parse_name(c.name).number for c in all_containers]
  318. return 1 if not numbers else max(numbers) + 1
  319. def _get_links(self, link_to_self):
  320. links = []
  321. for service, link_name in self.links:
  322. for container in service.containers():
  323. links.append((container.name, link_name or service.name))
  324. links.append((container.name, container.name))
  325. links.append((container.name, container.name_without_project))
  326. if link_to_self:
  327. for container in self.containers():
  328. links.append((container.name, self.name))
  329. links.append((container.name, container.name))
  330. links.append((container.name, container.name_without_project))
  331. for external_link in self.external_links:
  332. if ':' not in external_link:
  333. link_name = external_link
  334. else:
  335. external_link, link_name = external_link.split(':')
  336. links.append((external_link, link_name))
  337. return links
  338. def _get_volumes_from(self):
  339. volumes_from = []
  340. for volume_source in self.volumes_from:
  341. if isinstance(volume_source, Service):
  342. containers = volume_source.containers(stopped=True)
  343. if not containers:
  344. volumes_from.append(volume_source.create_container().id)
  345. else:
  346. volumes_from.extend(map(attrgetter('id'), containers))
  347. elif isinstance(volume_source, Container):
  348. volumes_from.append(volume_source.id)
  349. return volumes_from
  350. def _get_container_create_options(self, override_options, one_off=False):
  351. container_options = dict(
  352. (k, self.options[k])
  353. for k in DOCKER_CONFIG_KEYS if k in self.options)
  354. container_options.update(override_options)
  355. container_options['name'] = self._next_container_name(
  356. self.containers(stopped=True, one_off=one_off),
  357. one_off)
  358. # If a qualified hostname was given, split it into an
  359. # unqualified hostname and a domainname unless domainname
  360. # was also given explicitly. This matches the behavior of
  361. # the official Docker CLI in that scenario.
  362. if ('hostname' in container_options
  363. and 'domainname' not in container_options
  364. and '.' in container_options['hostname']):
  365. parts = container_options['hostname'].partition('.')
  366. container_options['hostname'] = parts[0]
  367. container_options['domainname'] = parts[2]
  368. if 'ports' in container_options or 'expose' in self.options:
  369. ports = []
  370. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  371. for port in all_ports:
  372. port = str(port)
  373. if ':' in port:
  374. port = port.split(':')[-1]
  375. if '/' in port:
  376. port = tuple(port.split('/'))
  377. ports.append(port)
  378. container_options['ports'] = ports
  379. if 'volumes' in container_options:
  380. container_options['volumes'] = dict(
  381. (parse_volume_spec(v).internal, {})
  382. for v in container_options['volumes'])
  383. container_options['environment'] = merge_environment(container_options)
  384. if self.can_be_built():
  385. container_options['image'] = self.full_name
  386. else:
  387. container_options['image'] = self._get_image_name(container_options['image'])
  388. # Delete options which are only used when starting
  389. for key in DOCKER_START_KEYS:
  390. container_options.pop(key, None)
  391. return container_options
  392. def _get_image_name(self, image):
  393. repo, tag = parse_repository_tag(image)
  394. if tag == "":
  395. tag = "latest"
  396. return '%s:%s' % (repo, tag)
  397. def build(self, no_cache=False):
  398. log.info('Building %s...' % self.name)
  399. build_output = self.client.build(
  400. self.options['build'],
  401. tag=self.full_name,
  402. stream=True,
  403. rm=True,
  404. nocache=no_cache,
  405. )
  406. try:
  407. all_events = stream_output(build_output, sys.stdout)
  408. except StreamOutputError, e:
  409. raise BuildError(self, unicode(e))
  410. image_id = None
  411. for event in all_events:
  412. if 'stream' in event:
  413. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  414. if match:
  415. image_id = match.group(1)
  416. if image_id is None:
  417. raise BuildError(self, event if all_events else 'Unknown')
  418. return image_id
  419. def can_be_built(self):
  420. return 'build' in self.options
  421. @property
  422. def full_name(self):
  423. """
  424. The tag to give to images built for this service.
  425. """
  426. return '%s_%s' % (self.project, self.name)
  427. def can_be_scaled(self):
  428. for port in self.options.get('ports', []):
  429. if ':' in str(port):
  430. return False
  431. return True
  432. def pull(self, insecure_registry=False):
  433. if 'image' in self.options:
  434. image_name = self._get_image_name(self.options['image'])
  435. log.info('Pulling %s (%s)...' % (self.name, image_name))
  436. self.client.pull(
  437. image_name,
  438. insecure_registry=insecure_registry
  439. )
  440. def get_container_data_volumes(container, volumes_option):
  441. """Find the container data volumes that are in `volumes_option`, and return
  442. a mapping of volume bindings for those volumes.
  443. """
  444. volumes = []
  445. for volume in volumes_option or []:
  446. volume = parse_volume_spec(volume)
  447. # No need to preserve host volumes
  448. if volume.external:
  449. continue
  450. volume_path = (container.get('Volumes') or {}).get(volume.internal)
  451. # New volume, doesn't exist in the old container
  452. if not volume_path:
  453. continue
  454. # Copy existing volume from old container
  455. volume = volume._replace(external=volume_path)
  456. volumes.append(build_volume_binding(volume))
  457. return dict(volumes)
  458. def get_volume_bindings(volumes_option, intermediate_container):
  459. """Return a list of volume bindings for a container. Container data volume
  460. bindings are replaced by those in the intermediate container.
  461. """
  462. volume_bindings = dict(
  463. build_volume_binding(parse_volume_spec(volume))
  464. for volume in volumes_option or []
  465. if ':' in volume)
  466. if intermediate_container:
  467. volume_bindings.update(
  468. get_container_data_volumes(intermediate_container, volumes_option))
  469. return volume_bindings
  470. NAME_RE = re.compile(r'^([^_]+)_([^_]+)_(run_)?(\d+)$')
  471. def is_valid_name(name, one_off=False):
  472. match = NAME_RE.match(name)
  473. if match is None:
  474. return False
  475. if one_off:
  476. return match.group(3) == 'run_'
  477. else:
  478. return match.group(3) is None
  479. def parse_name(name):
  480. match = NAME_RE.match(name)
  481. (project, service_name, _, suffix) = match.groups()
  482. return ServiceName(project, service_name, int(suffix))
  483. def get_container_name(container):
  484. if not container.get('Name') and not container.get('Names'):
  485. return None
  486. # inspect
  487. if 'Name' in container:
  488. return container['Name']
  489. # ps
  490. for name in container['Names']:
  491. if len(name.split('/')) == 2:
  492. return name[1:]
  493. def parse_restart_spec(restart_config):
  494. if not restart_config:
  495. return None
  496. parts = restart_config.split(':')
  497. if len(parts) > 2:
  498. raise ConfigError("Restart %s has incorrect format, should be "
  499. "mode[:max_retry]" % restart_config)
  500. if len(parts) == 2:
  501. name, max_retry_count = parts
  502. else:
  503. name, = parts
  504. max_retry_count = 0
  505. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  506. def parse_volume_spec(volume_config):
  507. parts = volume_config.split(':')
  508. if len(parts) > 3:
  509. raise ConfigError("Volume %s has incorrect format, should be "
  510. "external:internal[:mode]" % volume_config)
  511. if len(parts) == 1:
  512. return VolumeSpec(None, parts[0], 'rw')
  513. if len(parts) == 2:
  514. parts.append('rw')
  515. external, internal, mode = parts
  516. if mode not in ('rw', 'ro'):
  517. raise ConfigError("Volume %s has invalid mode (%s), should be "
  518. "one of: rw, ro." % (volume_config, mode))
  519. return VolumeSpec(external, internal, mode)
  520. def parse_repository_tag(s):
  521. if ":" not in s:
  522. return s, ""
  523. repo, tag = s.rsplit(":", 1)
  524. if "/" in tag:
  525. return s, ""
  526. return repo, tag
  527. def build_volume_binding(volume_spec):
  528. internal = {'bind': volume_spec.internal, 'ro': volume_spec.mode == 'ro'}
  529. external = os.path.expanduser(volume_spec.external)
  530. return os.path.abspath(os.path.expandvars(external)), internal
  531. def build_port_bindings(ports):
  532. port_bindings = {}
  533. for port in ports:
  534. internal_port, external = split_port(port)
  535. if internal_port in port_bindings:
  536. port_bindings[internal_port].append(external)
  537. else:
  538. port_bindings[internal_port] = [external]
  539. return port_bindings
  540. def split_port(port):
  541. parts = str(port).split(':')
  542. if not 1 <= len(parts) <= 3:
  543. raise ConfigError('Invalid port "%s", should be '
  544. '[[remote_ip:]remote_port:]port[/protocol]' % port)
  545. if len(parts) == 1:
  546. internal_port, = parts
  547. return internal_port, None
  548. if len(parts) == 2:
  549. external_port, internal_port = parts
  550. return internal_port, external_port
  551. external_ip, external_port, internal_port = parts
  552. return internal_port, (external_ip, external_port or None)
  553. def merge_environment(options):
  554. env = {}
  555. if 'env_file' in options:
  556. if isinstance(options['env_file'], list):
  557. for f in options['env_file']:
  558. env.update(env_vars_from_file(f))
  559. else:
  560. env.update(env_vars_from_file(options['env_file']))
  561. if 'environment' in options:
  562. if isinstance(options['environment'], list):
  563. env.update(dict(split_env(e) for e in options['environment']))
  564. else:
  565. env.update(options['environment'])
  566. return dict(resolve_env(k, v) for k, v in env.iteritems())
  567. def split_env(env):
  568. if '=' in env:
  569. return env.split('=', 1)
  570. else:
  571. return env, None
  572. def resolve_env(key, val):
  573. if val is not None:
  574. return key, val
  575. elif key in os.environ:
  576. return key, os.environ[key]
  577. else:
  578. return key, ''
  579. def env_vars_from_file(filename):
  580. """
  581. Read in a line delimited file of environment variables.
  582. """
  583. env = {}
  584. for line in open(filename, 'r'):
  585. line = line.strip()
  586. if line and not line.startswith('#'):
  587. k, v = split_env(line)
  588. env[k] = v
  589. return env