service.py 24 KB

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