service.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import os
  5. import re
  6. import sys
  7. from collections import namedtuple
  8. from operator import attrgetter
  9. import enum
  10. import six
  11. from docker.errors import APIError
  12. from docker.utils import LogConfig
  13. from docker.utils.ports import build_port_bindings
  14. from docker.utils.ports import split_port
  15. from . import __version__
  16. from .config import DOCKER_CONFIG_KEYS
  17. from .config import merge_environment
  18. from .config.validation import VALID_NAME_CHARS
  19. from .const import DEFAULT_TIMEOUT
  20. from .const import IS_WINDOWS_PLATFORM
  21. from .const import LABEL_CONFIG_HASH
  22. from .const import LABEL_CONTAINER_NUMBER
  23. from .const import LABEL_ONE_OFF
  24. from .const import LABEL_PROJECT
  25. from .const import LABEL_SERVICE
  26. from .const import LABEL_VERSION
  27. from .container import Container
  28. from .legacy import check_for_legacy_containers
  29. from .progress_stream import stream_output
  30. from .progress_stream import StreamOutputError
  31. from .utils import json_hash
  32. from .utils import parallel_execute
  33. log = logging.getLogger(__name__)
  34. DOCKER_START_KEYS = [
  35. 'cap_add',
  36. 'cap_drop',
  37. 'cgroup_parent',
  38. 'devices',
  39. 'dns',
  40. 'dns_search',
  41. 'env_file',
  42. 'extra_hosts',
  43. 'ipc',
  44. 'read_only',
  45. 'net',
  46. 'log_driver',
  47. 'log_opt',
  48. 'mem_limit',
  49. 'memswap_limit',
  50. 'pid',
  51. 'privileged',
  52. 'restart',
  53. 'volumes_from',
  54. 'security_opt',
  55. ]
  56. class BuildError(Exception):
  57. def __init__(self, service, reason):
  58. self.service = service
  59. self.reason = reason
  60. class ConfigError(ValueError):
  61. pass
  62. class NeedsBuildError(Exception):
  63. def __init__(self, service):
  64. self.service = service
  65. class NoSuchImageError(Exception):
  66. pass
  67. VolumeSpec = namedtuple('VolumeSpec', 'external internal mode')
  68. VolumeFromSpec = namedtuple('VolumeFromSpec', 'source mode')
  69. ServiceName = namedtuple('ServiceName', 'project service number')
  70. ConvergencePlan = namedtuple('ConvergencePlan', 'action containers')
  71. @enum.unique
  72. class ConvergenceStrategy(enum.Enum):
  73. """Enumeration for all possible convergence strategies. Values refer to
  74. when containers should be recreated.
  75. """
  76. changed = 1
  77. always = 2
  78. never = 3
  79. @property
  80. def allows_recreate(self):
  81. return self is not type(self).never
  82. class Service(object):
  83. def __init__(
  84. self,
  85. name,
  86. client=None,
  87. project='default',
  88. use_networking=False,
  89. links=None,
  90. volumes_from=None,
  91. net=None,
  92. **options
  93. ):
  94. if not re.match('^%s+$' % VALID_NAME_CHARS, project):
  95. raise ConfigError('Invalid project name "%s" - only %s are allowed' % (project, VALID_NAME_CHARS))
  96. self.name = name
  97. self.client = client
  98. self.project = project
  99. self.use_networking = use_networking
  100. self.links = links or []
  101. self.volumes_from = volumes_from or []
  102. self.net = net or Net(None)
  103. self.options = options
  104. def containers(self, stopped=False, one_off=False, filters={}):
  105. filters.update({'label': self.labels(one_off=one_off)})
  106. containers = list(filter(None, [
  107. Container.from_ps(self.client, container)
  108. for container in self.client.containers(
  109. all=stopped,
  110. filters=filters)]))
  111. if not containers:
  112. check_for_legacy_containers(
  113. self.client,
  114. self.project,
  115. [self.name],
  116. )
  117. return containers
  118. def get_container(self, number=1):
  119. """Return a :class:`compose.container.Container` for this service. The
  120. container must be active, and match `number`.
  121. """
  122. labels = self.labels() + ['{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]
  123. for container in self.client.containers(filters={'label': labels}):
  124. return Container.from_ps(self.client, container)
  125. raise ValueError("No container found for %s_%s" % (self.name, number))
  126. def start(self, **options):
  127. for c in self.containers(stopped=True):
  128. self.start_container_if_stopped(c, **options)
  129. # TODO: remove these functions, project takes care of starting/stopping,
  130. def stop(self, **options):
  131. for c in self.containers():
  132. log.info("Stopping %s" % c.name)
  133. c.stop(**options)
  134. def pause(self, **options):
  135. for c in self.containers(filters={'status': 'running'}):
  136. log.info("Pausing %s" % c.name)
  137. c.pause(**options)
  138. def unpause(self, **options):
  139. for c in self.containers(filters={'status': 'paused'}):
  140. log.info("Unpausing %s" % c.name)
  141. c.unpause()
  142. def kill(self, **options):
  143. for c in self.containers():
  144. log.info("Killing %s" % c.name)
  145. c.kill(**options)
  146. def restart(self, **options):
  147. for c in self.containers():
  148. log.info("Restarting %s" % c.name)
  149. c.restart(**options)
  150. # end TODO
  151. def scale(self, desired_num, timeout=DEFAULT_TIMEOUT):
  152. """
  153. Adjusts the number of containers to the specified number and ensures
  154. they are running.
  155. - creates containers until there are at least `desired_num`
  156. - stops containers until there are at most `desired_num` running
  157. - starts containers until there are at least `desired_num` running
  158. - removes all stopped containers
  159. """
  160. if self.custom_container_name() and desired_num > 1:
  161. log.warn('The "%s" service is using the custom container name "%s". '
  162. 'Docker requires each container to have a unique name. '
  163. 'Remove the custom name to scale the service.'
  164. % (self.name, self.custom_container_name()))
  165. if self.specifies_host_port():
  166. log.warn('The "%s" service specifies a port on the host. If multiple containers '
  167. 'for this service are created on a single host, the port will clash.'
  168. % self.name)
  169. def create_and_start(service, number):
  170. container = service.create_container(number=number, quiet=True)
  171. container.start()
  172. return container
  173. running_containers = self.containers(stopped=False)
  174. num_running = len(running_containers)
  175. if desired_num == num_running:
  176. # do nothing as we already have the desired number
  177. log.info('Desired container number already achieved')
  178. return
  179. if desired_num > num_running:
  180. # we need to start/create until we have desired_num
  181. all_containers = self.containers(stopped=True)
  182. if num_running != len(all_containers):
  183. # we have some stopped containers, let's start them up again
  184. stopped_containers = sorted([c for c in all_containers if not c.is_running], key=attrgetter('number'))
  185. num_stopped = len(stopped_containers)
  186. if num_stopped + num_running > desired_num:
  187. num_to_start = desired_num - num_running
  188. containers_to_start = stopped_containers[:num_to_start]
  189. else:
  190. containers_to_start = stopped_containers
  191. parallel_execute(
  192. objects=containers_to_start,
  193. obj_callable=lambda c: c.start(),
  194. msg_index=lambda c: c.name,
  195. msg="Starting"
  196. )
  197. num_running += len(containers_to_start)
  198. num_to_create = desired_num - num_running
  199. next_number = self._next_container_number()
  200. container_numbers = [
  201. number for number in range(
  202. next_number, next_number + num_to_create
  203. )
  204. ]
  205. parallel_execute(
  206. objects=container_numbers,
  207. obj_callable=lambda n: create_and_start(service=self, number=n),
  208. msg_index=lambda n: n,
  209. msg="Creating and starting"
  210. )
  211. if desired_num < num_running:
  212. num_to_stop = num_running - desired_num
  213. sorted_running_containers = sorted(running_containers, key=attrgetter('number'))
  214. containers_to_stop = sorted_running_containers[-num_to_stop:]
  215. parallel_execute(
  216. objects=containers_to_stop,
  217. obj_callable=lambda c: c.stop(timeout=timeout),
  218. msg_index=lambda c: c.name,
  219. msg="Stopping"
  220. )
  221. self.remove_stopped()
  222. def remove_stopped(self, **options):
  223. containers = [c for c in self.containers(stopped=True) if not c.is_running]
  224. parallel_execute(
  225. objects=containers,
  226. obj_callable=lambda c: c.remove(**options),
  227. msg_index=lambda c: c.name,
  228. msg="Removing"
  229. )
  230. def create_container(self,
  231. one_off=False,
  232. do_build=True,
  233. previous_container=None,
  234. number=None,
  235. quiet=False,
  236. **override_options):
  237. """
  238. Create a container for this service. If the image doesn't exist, attempt to pull
  239. it.
  240. """
  241. self.ensure_image_exists(do_build=do_build)
  242. container_options = self._get_container_create_options(
  243. override_options,
  244. number or self._next_container_number(one_off=one_off),
  245. one_off=one_off,
  246. previous_container=previous_container,
  247. )
  248. if 'name' in container_options and not quiet:
  249. log.info("Creating %s" % container_options['name'])
  250. return Container.create(self.client, **container_options)
  251. def ensure_image_exists(self, do_build=True):
  252. try:
  253. self.image()
  254. return
  255. except NoSuchImageError:
  256. pass
  257. if self.can_be_built():
  258. if do_build:
  259. self.build()
  260. else:
  261. raise NeedsBuildError(self)
  262. else:
  263. self.pull()
  264. def image(self):
  265. try:
  266. return self.client.inspect_image(self.image_name)
  267. except APIError as e:
  268. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  269. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  270. else:
  271. raise
  272. @property
  273. def image_name(self):
  274. if self.can_be_built():
  275. return self.full_name
  276. else:
  277. return self.options['image']
  278. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  279. containers = self.containers(stopped=True)
  280. if not containers:
  281. return ConvergencePlan('create', [])
  282. if strategy is ConvergenceStrategy.never:
  283. return ConvergencePlan('start', containers)
  284. if (
  285. strategy is ConvergenceStrategy.always or
  286. self._containers_have_diverged(containers)
  287. ):
  288. return ConvergencePlan('recreate', containers)
  289. stopped = [c for c in containers if not c.is_running]
  290. if stopped:
  291. return ConvergencePlan('start', stopped)
  292. return ConvergencePlan('noop', containers)
  293. def _containers_have_diverged(self, containers):
  294. config_hash = None
  295. try:
  296. config_hash = self.config_hash
  297. except NoSuchImageError as e:
  298. log.debug(
  299. 'Service %s has diverged: %s',
  300. self.name, six.text_type(e),
  301. )
  302. return True
  303. has_diverged = False
  304. for c in containers:
  305. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  306. if container_config_hash != config_hash:
  307. log.debug(
  308. '%s has diverged: %s != %s',
  309. c.name, container_config_hash, config_hash,
  310. )
  311. has_diverged = True
  312. return has_diverged
  313. def execute_convergence_plan(self,
  314. plan,
  315. do_build=True,
  316. timeout=DEFAULT_TIMEOUT,
  317. detached=False):
  318. (action, containers) = plan
  319. should_attach_logs = not detached
  320. if action == 'create':
  321. container = self.create_container(do_build=do_build)
  322. if should_attach_logs:
  323. container.attach_log_stream()
  324. self.start_container(container)
  325. return [container]
  326. elif action == 'recreate':
  327. return [
  328. self.recreate_container(
  329. container,
  330. timeout=timeout,
  331. attach_logs=should_attach_logs
  332. )
  333. for container in containers
  334. ]
  335. elif action == 'start':
  336. for container in containers:
  337. self.start_container_if_stopped(container, attach_logs=should_attach_logs)
  338. return containers
  339. elif action == 'noop':
  340. for c in containers:
  341. log.info("%s is up-to-date" % c.name)
  342. return containers
  343. else:
  344. raise Exception("Invalid action: {}".format(action))
  345. def _recreate_stop_container(self, container, timeout):
  346. try:
  347. container.stop(timeout=timeout)
  348. except APIError as e:
  349. if (e.response.status_code == 500
  350. and e.explanation
  351. and 'no such process' in str(e.explanation)):
  352. pass
  353. else:
  354. raise
  355. def recreate_container(self,
  356. container,
  357. timeout=DEFAULT_TIMEOUT,
  358. attach_logs=False):
  359. """Recreate a container.
  360. The original container is renamed to a temporary name so that data
  361. volumes can be copied to the new container, before the original
  362. container is removed.
  363. """
  364. log.info("Recreating %s" % container.name)
  365. self._recreate_stop_container(container, timeout)
  366. container.rename_to_tmp_name()
  367. new_container = self.create_container(
  368. do_build=False,
  369. previous_container=container,
  370. number=container.labels.get(LABEL_CONTAINER_NUMBER),
  371. quiet=True,
  372. )
  373. if attach_logs:
  374. new_container.attach_log_stream()
  375. self.start_container(new_container)
  376. container.remove()
  377. return new_container
  378. def start_container_if_stopped(self, container, attach_logs=False):
  379. if container.is_running:
  380. return container
  381. else:
  382. log.info("Starting %s" % container.name)
  383. if attach_logs:
  384. container.attach_log_stream()
  385. return self.start_container(container)
  386. def start_container(self, container):
  387. container.start()
  388. return container
  389. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  390. for c in self.duplicate_containers():
  391. log.info('Removing %s' % c.name)
  392. c.stop(timeout=timeout)
  393. c.remove()
  394. def duplicate_containers(self):
  395. containers = sorted(
  396. self.containers(stopped=True),
  397. key=lambda c: c.get('Created'),
  398. )
  399. numbers = set()
  400. for c in containers:
  401. if c.number in numbers:
  402. yield c
  403. else:
  404. numbers.add(c.number)
  405. @property
  406. def config_hash(self):
  407. return json_hash(self.config_dict())
  408. def config_dict(self):
  409. return {
  410. 'options': self.options,
  411. 'image_id': self.image()['Id'],
  412. 'links': self.get_link_names(),
  413. 'net': self.net.id,
  414. 'volumes_from': self.get_volumes_from_names(),
  415. }
  416. def get_dependency_names(self):
  417. net_name = self.net.service_name
  418. return (self.get_linked_service_names() +
  419. self.get_volumes_from_names() +
  420. ([net_name] if net_name else []))
  421. def get_linked_service_names(self):
  422. return [service.name for (service, _) in self.links]
  423. def get_link_names(self):
  424. return [(service.name, alias) for service, alias in self.links]
  425. def get_volumes_from_names(self):
  426. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  427. def get_container_name(self, number, one_off=False):
  428. # TODO: Implement issue #652 here
  429. return build_container_name(self.project, self.name, number, one_off)
  430. # TODO: this would benefit from github.com/docker/docker/pull/11943
  431. # to remove the need to inspect every container
  432. def _next_container_number(self, one_off=False):
  433. containers = filter(None, [
  434. Container.from_ps(self.client, container)
  435. for container in self.client.containers(
  436. all=True,
  437. filters={'label': self.labels(one_off=one_off)})
  438. ])
  439. numbers = [c.number for c in containers]
  440. return 1 if not numbers else max(numbers) + 1
  441. def _get_links(self, link_to_self):
  442. links = []
  443. for service, link_name in self.links:
  444. for container in service.containers():
  445. links.append((container.name, link_name or service.name))
  446. links.append((container.name, container.name))
  447. links.append((container.name, container.name_without_project))
  448. if link_to_self:
  449. for container in self.containers():
  450. links.append((container.name, self.name))
  451. links.append((container.name, container.name))
  452. links.append((container.name, container.name_without_project))
  453. for external_link in self.options.get('external_links') or []:
  454. if ':' not in external_link:
  455. link_name = external_link
  456. else:
  457. external_link, link_name = external_link.split(':')
  458. links.append((external_link, link_name))
  459. return links
  460. def _get_volumes_from(self):
  461. volumes_from = []
  462. for volume_from_spec in self.volumes_from:
  463. volumes = build_volume_from(volume_from_spec)
  464. volumes_from.extend(volumes)
  465. return volumes_from
  466. def _get_container_create_options(
  467. self,
  468. override_options,
  469. number,
  470. one_off=False,
  471. previous_container=None):
  472. add_config_hash = (not one_off and not override_options)
  473. container_options = dict(
  474. (k, self.options[k])
  475. for k in DOCKER_CONFIG_KEYS if k in self.options)
  476. container_options.update(override_options)
  477. if self.custom_container_name() and not one_off:
  478. container_options['name'] = self.custom_container_name()
  479. elif not container_options.get('name'):
  480. container_options['name'] = self.get_container_name(number, one_off)
  481. if 'detach' not in container_options:
  482. container_options['detach'] = True
  483. # If a qualified hostname was given, split it into an
  484. # unqualified hostname and a domainname unless domainname
  485. # was also given explicitly. This matches the behavior of
  486. # the official Docker CLI in that scenario.
  487. if ('hostname' in container_options
  488. and 'domainname' not in container_options
  489. and '.' in container_options['hostname']):
  490. parts = container_options['hostname'].partition('.')
  491. container_options['hostname'] = parts[0]
  492. container_options['domainname'] = parts[2]
  493. if 'hostname' not in container_options and self.use_networking:
  494. container_options['hostname'] = self.name
  495. if 'ports' in container_options or 'expose' in self.options:
  496. ports = []
  497. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  498. for port_range in all_ports:
  499. internal_range, _ = split_port(port_range)
  500. for port in internal_range:
  501. port = str(port)
  502. if '/' in port:
  503. port = tuple(port.split('/'))
  504. ports.append(port)
  505. container_options['ports'] = ports
  506. override_options['binds'] = merge_volume_bindings(
  507. container_options.get('volumes') or [],
  508. previous_container)
  509. if 'volumes' in container_options:
  510. container_options['volumes'] = dict(
  511. (parse_volume_spec(v).internal, {})
  512. for v in container_options['volumes'])
  513. container_options['environment'] = merge_environment(
  514. self.options.get('environment'),
  515. override_options.get('environment'))
  516. if previous_container:
  517. container_options['environment']['affinity:container'] = ('=' + previous_container.id)
  518. container_options['image'] = self.image_name
  519. container_options['labels'] = build_container_labels(
  520. container_options.get('labels', {}),
  521. self.labels(one_off=one_off),
  522. number,
  523. self.config_hash if add_config_hash else None)
  524. # Delete options which are only used when starting
  525. for key in DOCKER_START_KEYS:
  526. container_options.pop(key, None)
  527. container_options['host_config'] = self._get_container_host_config(
  528. override_options,
  529. one_off=one_off)
  530. return container_options
  531. def _get_container_host_config(self, override_options, one_off=False):
  532. options = dict(self.options, **override_options)
  533. port_bindings = build_port_bindings(options.get('ports') or [])
  534. privileged = options.get('privileged', False)
  535. cap_add = options.get('cap_add', None)
  536. cap_drop = options.get('cap_drop', None)
  537. log_config = LogConfig(
  538. type=options.get('log_driver', ""),
  539. config=options.get('log_opt', None)
  540. )
  541. pid = options.get('pid', None)
  542. security_opt = options.get('security_opt', None)
  543. dns = options.get('dns', None)
  544. if isinstance(dns, six.string_types):
  545. dns = [dns]
  546. dns_search = options.get('dns_search', None)
  547. if isinstance(dns_search, six.string_types):
  548. dns_search = [dns_search]
  549. restart = parse_restart_spec(options.get('restart', None))
  550. extra_hosts = build_extra_hosts(options.get('extra_hosts', None))
  551. read_only = options.get('read_only', None)
  552. devices = options.get('devices', None)
  553. cgroup_parent = options.get('cgroup_parent', None)
  554. return self.client.create_host_config(
  555. links=self._get_links(link_to_self=one_off),
  556. port_bindings=port_bindings,
  557. binds=options.get('binds'),
  558. volumes_from=self._get_volumes_from(),
  559. privileged=privileged,
  560. network_mode=self.net.mode,
  561. devices=devices,
  562. dns=dns,
  563. dns_search=dns_search,
  564. restart_policy=restart,
  565. cap_add=cap_add,
  566. cap_drop=cap_drop,
  567. mem_limit=options.get('mem_limit'),
  568. memswap_limit=options.get('memswap_limit'),
  569. log_config=log_config,
  570. extra_hosts=extra_hosts,
  571. read_only=read_only,
  572. pid_mode=pid,
  573. security_opt=security_opt,
  574. ipc_mode=options.get('ipc'),
  575. cgroup_parent=cgroup_parent
  576. )
  577. def build(self, no_cache=False, pull=False):
  578. log.info('Building %s' % self.name)
  579. path = self.options['build']
  580. # python2 os.path() doesn't support unicode, so we need to encode it to
  581. # a byte string
  582. if not six.PY3:
  583. path = path.encode('utf8')
  584. build_output = self.client.build(
  585. path=path,
  586. tag=self.image_name,
  587. stream=True,
  588. rm=True,
  589. pull=pull,
  590. nocache=no_cache,
  591. dockerfile=self.options.get('dockerfile', None),
  592. )
  593. try:
  594. all_events = stream_output(build_output, sys.stdout)
  595. except StreamOutputError as e:
  596. raise BuildError(self, six.text_type(e))
  597. # Ensure the HTTP connection is not reused for another
  598. # streaming command, as the Docker daemon can sometimes
  599. # complain about it
  600. self.client.close()
  601. image_id = None
  602. for event in all_events:
  603. if 'stream' in event:
  604. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  605. if match:
  606. image_id = match.group(1)
  607. if image_id is None:
  608. raise BuildError(self, event if all_events else 'Unknown')
  609. return image_id
  610. def can_be_built(self):
  611. return 'build' in self.options
  612. @property
  613. def full_name(self):
  614. """
  615. The tag to give to images built for this service.
  616. """
  617. return '%s_%s' % (self.project, self.name)
  618. def labels(self, one_off=False):
  619. return [
  620. '{0}={1}'.format(LABEL_PROJECT, self.project),
  621. '{0}={1}'.format(LABEL_SERVICE, self.name),
  622. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  623. ]
  624. def custom_container_name(self):
  625. return self.options.get('container_name')
  626. def specifies_host_port(self):
  627. def has_host_port(binding):
  628. _, external_bindings = split_port(binding)
  629. # there are no external bindings
  630. if external_bindings is None:
  631. return False
  632. # we only need to check the first binding from the range
  633. external_binding = external_bindings[0]
  634. # non-tuple binding means there is a host port specified
  635. if not isinstance(external_binding, tuple):
  636. return True
  637. # extract actual host port from tuple of (host_ip, host_port)
  638. _, host_port = external_binding
  639. if host_port is not None:
  640. return True
  641. return False
  642. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  643. def pull(self, ignore_pull_failures=False):
  644. if 'image' not in self.options:
  645. return
  646. repo, tag, separator = parse_repository_tag(self.options['image'])
  647. tag = tag or 'latest'
  648. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  649. output = self.client.pull(
  650. repo,
  651. tag=tag,
  652. stream=True,
  653. )
  654. try:
  655. stream_output(output, sys.stdout)
  656. except StreamOutputError as e:
  657. if not ignore_pull_failures:
  658. raise
  659. else:
  660. log.error(six.text_type(e))
  661. class Net(object):
  662. """A `standard` network mode (ex: host, bridge)"""
  663. service_name = None
  664. def __init__(self, net):
  665. self.net = net
  666. @property
  667. def id(self):
  668. return self.net
  669. mode = id
  670. class ContainerNet(object):
  671. """A network mode that uses a container's network stack."""
  672. service_name = None
  673. def __init__(self, container):
  674. self.container = container
  675. @property
  676. def id(self):
  677. return self.container.id
  678. @property
  679. def mode(self):
  680. return 'container:' + self.container.id
  681. class ServiceNet(object):
  682. """A network mode that uses a service's network stack."""
  683. def __init__(self, service):
  684. self.service = service
  685. @property
  686. def id(self):
  687. return self.service.name
  688. service_name = id
  689. @property
  690. def mode(self):
  691. containers = self.service.containers()
  692. if containers:
  693. return 'container:' + containers[0].id
  694. log.warn("Warning: Service %s is trying to use reuse the network stack "
  695. "of another service that is not running." % (self.id))
  696. return None
  697. # Names
  698. def build_container_name(project, service, number, one_off=False):
  699. bits = [project, service]
  700. if one_off:
  701. bits.append('run')
  702. return '_'.join(bits + [str(number)])
  703. # Images
  704. def parse_repository_tag(repo_path):
  705. """Splits image identification into base image path, tag/digest
  706. and it's separator.
  707. Example:
  708. >>> parse_repository_tag('user/repo@sha256:digest')
  709. ('user/repo', 'sha256:digest', '@')
  710. >>> parse_repository_tag('user/repo:v1')
  711. ('user/repo', 'v1', ':')
  712. """
  713. tag_separator = ":"
  714. digest_separator = "@"
  715. if digest_separator in repo_path:
  716. repo, tag = repo_path.rsplit(digest_separator, 1)
  717. return repo, tag, digest_separator
  718. repo, tag = repo_path, ""
  719. if tag_separator in repo_path:
  720. repo, tag = repo_path.rsplit(tag_separator, 1)
  721. if "/" in tag:
  722. repo, tag = repo_path, ""
  723. return repo, tag, tag_separator
  724. # Volumes
  725. def merge_volume_bindings(volumes_option, previous_container):
  726. """Return a list of volume bindings for a container. Container data volumes
  727. are replaced by those from the previous container.
  728. """
  729. volume_bindings = dict(
  730. build_volume_binding(parse_volume_spec(volume))
  731. for volume in volumes_option or []
  732. if ':' in volume)
  733. if previous_container:
  734. volume_bindings.update(
  735. get_container_data_volumes(previous_container, volumes_option))
  736. return list(volume_bindings.values())
  737. def get_container_data_volumes(container, volumes_option):
  738. """Find the container data volumes that are in `volumes_option`, and return
  739. a mapping of volume bindings for those volumes.
  740. """
  741. volumes = []
  742. volumes_option = volumes_option or []
  743. container_volumes = container.get('Volumes') or {}
  744. image_volumes = container.image_config['ContainerConfig'].get('Volumes') or {}
  745. for volume in set(volumes_option + list(image_volumes)):
  746. volume = parse_volume_spec(volume)
  747. # No need to preserve host volumes
  748. if volume.external:
  749. continue
  750. volume_path = container_volumes.get(volume.internal)
  751. # New volume, doesn't exist in the old container
  752. if not volume_path:
  753. continue
  754. # Copy existing volume from old container
  755. volume = volume._replace(external=volume_path)
  756. volumes.append(build_volume_binding(volume))
  757. return dict(volumes)
  758. def build_volume_binding(volume_spec):
  759. return volume_spec.internal, "{}:{}:{}".format(*volume_spec)
  760. def normalize_paths_for_engine(external_path, internal_path):
  761. """Windows paths, c:\my\path\shiny, need to be changed to be compatible with
  762. the Engine. Volume paths are expected to be linux style /c/my/path/shiny/
  763. """
  764. if not IS_WINDOWS_PLATFORM:
  765. return external_path, internal_path
  766. if external_path:
  767. drive, tail = os.path.splitdrive(external_path)
  768. if drive:
  769. external_path = '/' + drive.lower().rstrip(':') + tail
  770. external_path = external_path.replace('\\', '/')
  771. return external_path, internal_path.replace('\\', '/')
  772. def parse_volume_spec(volume_config):
  773. """
  774. Parse a volume_config path and split it into external:internal[:mode]
  775. parts to be returned as a valid VolumeSpec.
  776. """
  777. if IS_WINDOWS_PLATFORM:
  778. # relative paths in windows expand to include the drive, eg C:\
  779. # so we join the first 2 parts back together to count as one
  780. drive, tail = os.path.splitdrive(volume_config)
  781. parts = tail.split(":")
  782. if drive:
  783. parts[0] = drive + parts[0]
  784. else:
  785. parts = volume_config.split(':')
  786. if len(parts) > 3:
  787. raise ConfigError("Volume %s has incorrect format, should be "
  788. "external:internal[:mode]" % volume_config)
  789. if len(parts) == 1:
  790. external, internal = normalize_paths_for_engine(None, os.path.normpath(parts[0]))
  791. else:
  792. external, internal = normalize_paths_for_engine(os.path.normpath(parts[0]), os.path.normpath(parts[1]))
  793. mode = 'rw'
  794. if len(parts) == 3:
  795. mode = parts[2]
  796. return VolumeSpec(external, internal, mode)
  797. def build_volume_from(volume_from_spec):
  798. """
  799. volume_from can be either a service or a container. We want to return the
  800. container.id and format it into a string complete with the mode.
  801. """
  802. if isinstance(volume_from_spec.source, Service):
  803. containers = volume_from_spec.source.containers(stopped=True)
  804. if not containers:
  805. return ["{}:{}".format(volume_from_spec.source.create_container().id, volume_from_spec.mode)]
  806. container = containers[0]
  807. return ["{}:{}".format(container.id, volume_from_spec.mode)]
  808. elif isinstance(volume_from_spec.source, Container):
  809. return ["{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)]
  810. def parse_volume_from_spec(volume_from_config):
  811. parts = volume_from_config.split(':')
  812. if len(parts) > 2:
  813. raise ConfigError("Volume %s has incorrect format, should be "
  814. "external:internal[:mode]" % volume_from_config)
  815. if len(parts) == 1:
  816. source = parts[0]
  817. mode = 'rw'
  818. else:
  819. source, mode = parts
  820. return VolumeFromSpec(source, mode)
  821. # Labels
  822. def build_container_labels(label_options, service_labels, number, config_hash):
  823. labels = dict(label_options or {})
  824. labels.update(label.split('=', 1) for label in service_labels)
  825. labels[LABEL_CONTAINER_NUMBER] = str(number)
  826. labels[LABEL_VERSION] = __version__
  827. if config_hash:
  828. log.debug("Added config hash: %s" % config_hash)
  829. labels[LABEL_CONFIG_HASH] = config_hash
  830. return labels
  831. # Restart policy
  832. def parse_restart_spec(restart_config):
  833. if not restart_config:
  834. return None
  835. parts = restart_config.split(':')
  836. if len(parts) > 2:
  837. raise ConfigError("Restart %s has incorrect format, should be "
  838. "mode[:max_retry]" % restart_config)
  839. if len(parts) == 2:
  840. name, max_retry_count = parts
  841. else:
  842. name, = parts
  843. max_retry_count = 0
  844. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  845. # Extra hosts
  846. def build_extra_hosts(extra_hosts_config):
  847. if not extra_hosts_config:
  848. return {}
  849. if isinstance(extra_hosts_config, list):
  850. extra_hosts_dict = {}
  851. for extra_hosts_line in extra_hosts_config:
  852. if not isinstance(extra_hosts_line, six.string_types):
  853. raise ConfigError(
  854. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  855. extra_hosts_config
  856. )
  857. host, ip = extra_hosts_line.split(':')
  858. extra_hosts_dict.update({host.strip(): ip.strip()})
  859. extra_hosts_config = extra_hosts_dict
  860. if isinstance(extra_hosts_config, dict):
  861. return extra_hosts_config
  862. raise ConfigError(
  863. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  864. extra_hosts_config
  865. )