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