service.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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(
  242. do_build=do_build,
  243. )
  244. container_options = self._get_container_create_options(
  245. override_options,
  246. number or self._next_container_number(one_off=one_off),
  247. one_off=one_off,
  248. previous_container=previous_container,
  249. )
  250. if 'name' in container_options and not quiet:
  251. log.info("Creating %s" % container_options['name'])
  252. return Container.create(self.client, **container_options)
  253. def ensure_image_exists(self,
  254. do_build=True):
  255. try:
  256. self.image()
  257. return
  258. except NoSuchImageError:
  259. pass
  260. if self.can_be_built():
  261. if do_build:
  262. self.build()
  263. else:
  264. raise NeedsBuildError(self)
  265. else:
  266. self.pull()
  267. def image(self):
  268. try:
  269. return self.client.inspect_image(self.image_name)
  270. except APIError as e:
  271. if e.response.status_code == 404 and e.explanation and 'No such image' in str(e.explanation):
  272. raise NoSuchImageError("Image '{}' not found".format(self.image_name))
  273. else:
  274. raise
  275. @property
  276. def image_name(self):
  277. if self.can_be_built():
  278. return self.full_name
  279. else:
  280. return self.options['image']
  281. def convergence_plan(self, strategy=ConvergenceStrategy.changed):
  282. containers = self.containers(stopped=True)
  283. if not containers:
  284. return ConvergencePlan('create', [])
  285. if strategy is ConvergenceStrategy.never:
  286. return ConvergencePlan('start', containers)
  287. if (
  288. strategy is ConvergenceStrategy.always or
  289. self._containers_have_diverged(containers)
  290. ):
  291. return ConvergencePlan('recreate', containers)
  292. stopped = [c for c in containers if not c.is_running]
  293. if stopped:
  294. return ConvergencePlan('start', stopped)
  295. return ConvergencePlan('noop', containers)
  296. def _containers_have_diverged(self, containers):
  297. config_hash = None
  298. try:
  299. config_hash = self.config_hash
  300. except NoSuchImageError as e:
  301. log.debug(
  302. 'Service %s has diverged: %s',
  303. self.name, six.text_type(e),
  304. )
  305. return True
  306. has_diverged = False
  307. for c in containers:
  308. container_config_hash = c.labels.get(LABEL_CONFIG_HASH, None)
  309. if container_config_hash != config_hash:
  310. log.debug(
  311. '%s has diverged: %s != %s',
  312. c.name, container_config_hash, config_hash,
  313. )
  314. has_diverged = True
  315. return has_diverged
  316. def execute_convergence_plan(self,
  317. plan,
  318. do_build=True,
  319. timeout=DEFAULT_TIMEOUT):
  320. (action, containers) = plan
  321. if action == 'create':
  322. container = self.create_container(
  323. do_build=do_build,
  324. )
  325. self.start_container(container)
  326. return [container]
  327. elif action == 'recreate':
  328. return [
  329. self.recreate_container(
  330. c,
  331. timeout=timeout
  332. )
  333. for c in containers
  334. ]
  335. elif action == 'start':
  336. for c in containers:
  337. self.start_container_if_stopped(c)
  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_container(self,
  346. container,
  347. timeout=DEFAULT_TIMEOUT):
  348. """Recreate a container.
  349. The original container is renamed to a temporary name so that data
  350. volumes can be copied to the new container, before the original
  351. container is removed.
  352. """
  353. log.info("Recreating %s" % container.name)
  354. try:
  355. container.stop(timeout=timeout)
  356. except APIError as e:
  357. if (e.response.status_code == 500
  358. and e.explanation
  359. and 'no such process' in str(e.explanation)):
  360. pass
  361. else:
  362. raise
  363. # Use a hopefully unique container name by prepending the short id
  364. self.client.rename(
  365. container.id,
  366. '%s_%s' % (container.short_id, container.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. self.start_container(new_container)
  374. container.remove()
  375. return new_container
  376. def start_container_if_stopped(self, container):
  377. if container.is_running:
  378. return container
  379. else:
  380. log.info("Starting %s" % container.name)
  381. return self.start_container(container)
  382. def start_container(self, container):
  383. container.start()
  384. return container
  385. def remove_duplicate_containers(self, timeout=DEFAULT_TIMEOUT):
  386. for c in self.duplicate_containers():
  387. log.info('Removing %s' % c.name)
  388. c.stop(timeout=timeout)
  389. c.remove()
  390. def duplicate_containers(self):
  391. containers = sorted(
  392. self.containers(stopped=True),
  393. key=lambda c: c.get('Created'),
  394. )
  395. numbers = set()
  396. for c in containers:
  397. if c.number in numbers:
  398. yield c
  399. else:
  400. numbers.add(c.number)
  401. @property
  402. def config_hash(self):
  403. return json_hash(self.config_dict())
  404. def config_dict(self):
  405. return {
  406. 'options': self.options,
  407. 'image_id': self.image()['Id'],
  408. 'links': self.get_link_names(),
  409. 'net': self.net.id,
  410. 'volumes_from': self.get_volumes_from_names(),
  411. }
  412. def get_dependency_names(self):
  413. net_name = self.net.service_name
  414. return (self.get_linked_service_names() +
  415. self.get_volumes_from_names() +
  416. ([net_name] if net_name else []))
  417. def get_linked_service_names(self):
  418. return [service.name for (service, _) in self.links]
  419. def get_link_names(self):
  420. return [(service.name, alias) for service, alias in self.links]
  421. def get_volumes_from_names(self):
  422. return [s.source.name for s in self.volumes_from if isinstance(s.source, Service)]
  423. def get_container_name(self, number, one_off=False):
  424. # TODO: Implement issue #652 here
  425. return build_container_name(self.project, self.name, number, one_off)
  426. # TODO: this would benefit from github.com/docker/docker/pull/11943
  427. # to remove the need to inspect every container
  428. def _next_container_number(self, one_off=False):
  429. containers = filter(None, [
  430. Container.from_ps(self.client, container)
  431. for container in self.client.containers(
  432. all=True,
  433. filters={'label': self.labels(one_off=one_off)})
  434. ])
  435. numbers = [c.number for c in containers]
  436. return 1 if not numbers else max(numbers) + 1
  437. def _get_links(self, link_to_self):
  438. links = []
  439. for service, link_name in self.links:
  440. for container in service.containers():
  441. links.append((container.name, link_name or service.name))
  442. links.append((container.name, container.name))
  443. links.append((container.name, container.name_without_project))
  444. if link_to_self:
  445. for container in self.containers():
  446. links.append((container.name, self.name))
  447. links.append((container.name, container.name))
  448. links.append((container.name, container.name_without_project))
  449. for external_link in self.options.get('external_links') or []:
  450. if ':' not in external_link:
  451. link_name = external_link
  452. else:
  453. external_link, link_name = external_link.split(':')
  454. links.append((external_link, link_name))
  455. return links
  456. def _get_volumes_from(self):
  457. volumes_from = []
  458. for volume_from_spec in self.volumes_from:
  459. volumes = build_volume_from(volume_from_spec)
  460. volumes_from.extend(volumes)
  461. return volumes_from
  462. def _get_container_create_options(
  463. self,
  464. override_options,
  465. number,
  466. one_off=False,
  467. previous_container=None):
  468. add_config_hash = (not one_off and not override_options)
  469. container_options = dict(
  470. (k, self.options[k])
  471. for k in DOCKER_CONFIG_KEYS if k in self.options)
  472. container_options.update(override_options)
  473. if self.custom_container_name() and not one_off:
  474. container_options['name'] = self.custom_container_name()
  475. elif not container_options.get('name'):
  476. container_options['name'] = self.get_container_name(number, one_off)
  477. if 'detach' not in container_options:
  478. container_options['detach'] = True
  479. # If a qualified hostname was given, split it into an
  480. # unqualified hostname and a domainname unless domainname
  481. # was also given explicitly. This matches the behavior of
  482. # the official Docker CLI in that scenario.
  483. if ('hostname' in container_options
  484. and 'domainname' not in container_options
  485. and '.' in container_options['hostname']):
  486. parts = container_options['hostname'].partition('.')
  487. container_options['hostname'] = parts[0]
  488. container_options['domainname'] = parts[2]
  489. if 'hostname' not in container_options and self.use_networking:
  490. container_options['hostname'] = self.name
  491. if 'ports' in container_options or 'expose' in self.options:
  492. ports = []
  493. all_ports = container_options.get('ports', []) + self.options.get('expose', [])
  494. for port_range in all_ports:
  495. internal_range, _ = split_port(port_range)
  496. for port in internal_range:
  497. port = str(port)
  498. if '/' in port:
  499. port = tuple(port.split('/'))
  500. ports.append(port)
  501. container_options['ports'] = ports
  502. override_options['binds'] = merge_volume_bindings(
  503. container_options.get('volumes') or [],
  504. previous_container)
  505. if 'volumes' in container_options:
  506. container_options['volumes'] = dict(
  507. (parse_volume_spec(v).internal, {})
  508. for v in container_options['volumes'])
  509. container_options['environment'] = merge_environment(
  510. self.options.get('environment'),
  511. override_options.get('environment'))
  512. if previous_container:
  513. container_options['environment']['affinity:container'] = ('=' + previous_container.id)
  514. container_options['image'] = self.image_name
  515. container_options['labels'] = build_container_labels(
  516. container_options.get('labels', {}),
  517. self.labels(one_off=one_off),
  518. number,
  519. self.config_hash if add_config_hash else None)
  520. # Delete options which are only used when starting
  521. for key in DOCKER_START_KEYS:
  522. container_options.pop(key, None)
  523. container_options['host_config'] = self._get_container_host_config(
  524. override_options,
  525. one_off=one_off)
  526. return container_options
  527. def _get_container_host_config(self, override_options, one_off=False):
  528. options = dict(self.options, **override_options)
  529. port_bindings = build_port_bindings(options.get('ports') or [])
  530. privileged = options.get('privileged', False)
  531. cap_add = options.get('cap_add', None)
  532. cap_drop = options.get('cap_drop', None)
  533. log_config = LogConfig(
  534. type=options.get('log_driver', ""),
  535. config=options.get('log_opt', None)
  536. )
  537. pid = options.get('pid', None)
  538. security_opt = options.get('security_opt', None)
  539. dns = options.get('dns', None)
  540. if isinstance(dns, six.string_types):
  541. dns = [dns]
  542. dns_search = options.get('dns_search', None)
  543. if isinstance(dns_search, six.string_types):
  544. dns_search = [dns_search]
  545. restart = parse_restart_spec(options.get('restart', None))
  546. extra_hosts = build_extra_hosts(options.get('extra_hosts', None))
  547. read_only = options.get('read_only', None)
  548. devices = options.get('devices', None)
  549. cgroup_parent = options.get('cgroup_parent', None)
  550. return self.client.create_host_config(
  551. links=self._get_links(link_to_self=one_off),
  552. port_bindings=port_bindings,
  553. binds=options.get('binds'),
  554. volumes_from=self._get_volumes_from(),
  555. privileged=privileged,
  556. network_mode=self.net.mode,
  557. devices=devices,
  558. dns=dns,
  559. dns_search=dns_search,
  560. restart_policy=restart,
  561. cap_add=cap_add,
  562. cap_drop=cap_drop,
  563. mem_limit=options.get('mem_limit'),
  564. memswap_limit=options.get('memswap_limit'),
  565. log_config=log_config,
  566. extra_hosts=extra_hosts,
  567. read_only=read_only,
  568. pid_mode=pid,
  569. security_opt=security_opt,
  570. ipc_mode=options.get('ipc'),
  571. cgroup_parent=cgroup_parent
  572. )
  573. def build(self, no_cache=False, pull=False):
  574. log.info('Building %s' % self.name)
  575. path = self.options['build']
  576. # python2 os.path() doesn't support unicode, so we need to encode it to
  577. # a byte string
  578. if not six.PY3:
  579. path = path.encode('utf8')
  580. build_output = self.client.build(
  581. path=path,
  582. tag=self.image_name,
  583. stream=True,
  584. rm=True,
  585. pull=pull,
  586. nocache=no_cache,
  587. dockerfile=self.options.get('dockerfile', None),
  588. )
  589. try:
  590. all_events = stream_output(build_output, sys.stdout)
  591. except StreamOutputError as e:
  592. raise BuildError(self, six.text_type(e))
  593. # Ensure the HTTP connection is not reused for another
  594. # streaming command, as the Docker daemon can sometimes
  595. # complain about it
  596. self.client.close()
  597. image_id = None
  598. for event in all_events:
  599. if 'stream' in event:
  600. match = re.search(r'Successfully built ([0-9a-f]+)', event.get('stream', ''))
  601. if match:
  602. image_id = match.group(1)
  603. if image_id is None:
  604. raise BuildError(self, event if all_events else 'Unknown')
  605. return image_id
  606. def can_be_built(self):
  607. return 'build' in self.options
  608. @property
  609. def full_name(self):
  610. """
  611. The tag to give to images built for this service.
  612. """
  613. return '%s_%s' % (self.project, self.name)
  614. def labels(self, one_off=False):
  615. return [
  616. '{0}={1}'.format(LABEL_PROJECT, self.project),
  617. '{0}={1}'.format(LABEL_SERVICE, self.name),
  618. '{0}={1}'.format(LABEL_ONE_OFF, "True" if one_off else "False")
  619. ]
  620. def custom_container_name(self):
  621. return self.options.get('container_name')
  622. def specifies_host_port(self):
  623. def has_host_port(binding):
  624. _, external_bindings = split_port(binding)
  625. # there are no external bindings
  626. if external_bindings is None:
  627. return False
  628. # we only need to check the first binding from the range
  629. external_binding = external_bindings[0]
  630. # non-tuple binding means there is a host port specified
  631. if not isinstance(external_binding, tuple):
  632. return True
  633. # extract actual host port from tuple of (host_ip, host_port)
  634. _, host_port = external_binding
  635. if host_port is not None:
  636. return True
  637. return False
  638. return any(has_host_port(binding) for binding in self.options.get('ports', []))
  639. def pull(self, ignore_pull_failures=False):
  640. if 'image' not in self.options:
  641. return
  642. repo, tag, separator = parse_repository_tag(self.options['image'])
  643. tag = tag or 'latest'
  644. log.info('Pulling %s (%s%s%s)...' % (self.name, repo, separator, tag))
  645. output = self.client.pull(
  646. repo,
  647. tag=tag,
  648. stream=True,
  649. )
  650. try:
  651. stream_output(output, sys.stdout)
  652. except StreamOutputError as e:
  653. if not ignore_pull_failures:
  654. raise
  655. else:
  656. log.error(six.text_type(e))
  657. class Net(object):
  658. """A `standard` network mode (ex: host, bridge)"""
  659. service_name = None
  660. def __init__(self, net):
  661. self.net = net
  662. @property
  663. def id(self):
  664. return self.net
  665. mode = id
  666. class ContainerNet(object):
  667. """A network mode that uses a container's network stack."""
  668. service_name = None
  669. def __init__(self, container):
  670. self.container = container
  671. @property
  672. def id(self):
  673. return self.container.id
  674. @property
  675. def mode(self):
  676. return 'container:' + self.container.id
  677. class ServiceNet(object):
  678. """A network mode that uses a service's network stack."""
  679. def __init__(self, service):
  680. self.service = service
  681. @property
  682. def id(self):
  683. return self.service.name
  684. service_name = id
  685. @property
  686. def mode(self):
  687. containers = self.service.containers()
  688. if containers:
  689. return 'container:' + containers[0].id
  690. log.warn("Warning: Service %s is trying to use reuse the network stack "
  691. "of another service that is not running." % (self.id))
  692. return None
  693. # Names
  694. def build_container_name(project, service, number, one_off=False):
  695. bits = [project, service]
  696. if one_off:
  697. bits.append('run')
  698. return '_'.join(bits + [str(number)])
  699. # Images
  700. def parse_repository_tag(repo_path):
  701. """Splits image identification into base image path, tag/digest
  702. and it's separator.
  703. Example:
  704. >>> parse_repository_tag('user/repo@sha256:digest')
  705. ('user/repo', 'sha256:digest', '@')
  706. >>> parse_repository_tag('user/repo:v1')
  707. ('user/repo', 'v1', ':')
  708. """
  709. tag_separator = ":"
  710. digest_separator = "@"
  711. if digest_separator in repo_path:
  712. repo, tag = repo_path.rsplit(digest_separator, 1)
  713. return repo, tag, digest_separator
  714. repo, tag = repo_path, ""
  715. if tag_separator in repo_path:
  716. repo, tag = repo_path.rsplit(tag_separator, 1)
  717. if "/" in tag:
  718. repo, tag = repo_path, ""
  719. return repo, tag, tag_separator
  720. # Volumes
  721. def merge_volume_bindings(volumes_option, previous_container):
  722. """Return a list of volume bindings for a container. Container data volumes
  723. are replaced by those from the previous container.
  724. """
  725. volume_bindings = dict(
  726. build_volume_binding(parse_volume_spec(volume))
  727. for volume in volumes_option or []
  728. if ':' in volume)
  729. if previous_container:
  730. volume_bindings.update(
  731. get_container_data_volumes(previous_container, volumes_option))
  732. return list(volume_bindings.values())
  733. def get_container_data_volumes(container, volumes_option):
  734. """Find the container data volumes that are in `volumes_option`, and return
  735. a mapping of volume bindings for those volumes.
  736. """
  737. volumes = []
  738. volumes_option = volumes_option or []
  739. container_volumes = container.get('Volumes') or {}
  740. image_volumes = container.image_config['ContainerConfig'].get('Volumes') or {}
  741. for volume in set(volumes_option + list(image_volumes)):
  742. volume = parse_volume_spec(volume)
  743. # No need to preserve host volumes
  744. if volume.external:
  745. continue
  746. volume_path = container_volumes.get(volume.internal)
  747. # New volume, doesn't exist in the old container
  748. if not volume_path:
  749. continue
  750. # Copy existing volume from old container
  751. volume = volume._replace(external=volume_path)
  752. volumes.append(build_volume_binding(volume))
  753. return dict(volumes)
  754. def build_volume_binding(volume_spec):
  755. return volume_spec.internal, "{}:{}:{}".format(*volume_spec)
  756. def normalize_paths_for_engine(external_path, internal_path):
  757. """
  758. Windows paths, c:\my\path\shiny, need to be changed to be compatible with
  759. the Engine. Volume paths are expected to be linux style /c/my/path/shiny/
  760. """
  761. if IS_WINDOWS_PLATFORM:
  762. if external_path:
  763. drive, tail = os.path.splitdrive(external_path)
  764. if drive:
  765. reformatted_drive = "/{}".format(drive.replace(":", ""))
  766. external_path = reformatted_drive + tail
  767. external_path = "/".join(external_path.split("\\"))
  768. return external_path, "/".join(internal_path.split("\\"))
  769. else:
  770. return external_path, internal_path
  771. def parse_volume_spec(volume_config):
  772. """
  773. Parse a volume_config path and split it into external:internal[:mode]
  774. parts to be returned as a valid VolumeSpec.
  775. """
  776. if IS_WINDOWS_PLATFORM:
  777. # relative paths in windows expand to include the drive, eg C:\
  778. # so we join the first 2 parts back together to count as one
  779. drive, tail = os.path.splitdrive(volume_config)
  780. parts = tail.split(":")
  781. if drive:
  782. parts[0] = drive + parts[0]
  783. else:
  784. parts = volume_config.split(':')
  785. if len(parts) > 3:
  786. raise ConfigError("Volume %s has incorrect format, should be "
  787. "external:internal[:mode]" % volume_config)
  788. if len(parts) == 1:
  789. external, internal = normalize_paths_for_engine(None, os.path.normpath(parts[0]))
  790. else:
  791. external, internal = normalize_paths_for_engine(os.path.normpath(parts[0]), os.path.normpath(parts[1]))
  792. mode = 'rw'
  793. if len(parts) == 3:
  794. mode = parts[2]
  795. return VolumeSpec(external, internal, mode)
  796. def build_volume_from(volume_from_spec):
  797. """
  798. volume_from can be either a service or a container. We want to return the
  799. container.id and format it into a string complete with the mode.
  800. """
  801. if isinstance(volume_from_spec.source, Service):
  802. containers = volume_from_spec.source.containers(stopped=True)
  803. if not containers:
  804. return ["{}:{}".format(volume_from_spec.source.create_container().id, volume_from_spec.mode)]
  805. container = containers[0]
  806. return ["{}:{}".format(container.id, volume_from_spec.mode)]
  807. elif isinstance(volume_from_spec.source, Container):
  808. return ["{}:{}".format(volume_from_spec.source.id, volume_from_spec.mode)]
  809. def parse_volume_from_spec(volume_from_config):
  810. parts = volume_from_config.split(':')
  811. if len(parts) > 2:
  812. raise ConfigError("Volume %s has incorrect format, should be "
  813. "external:internal[:mode]" % volume_from_config)
  814. if len(parts) == 1:
  815. source = parts[0]
  816. mode = 'rw'
  817. else:
  818. source, mode = parts
  819. return VolumeFromSpec(source, mode)
  820. # Labels
  821. def build_container_labels(label_options, service_labels, number, config_hash):
  822. labels = dict(label_options or {})
  823. labels.update(label.split('=', 1) for label in service_labels)
  824. labels[LABEL_CONTAINER_NUMBER] = str(number)
  825. labels[LABEL_VERSION] = __version__
  826. if config_hash:
  827. log.debug("Added config hash: %s" % config_hash)
  828. labels[LABEL_CONFIG_HASH] = config_hash
  829. return labels
  830. # Restart policy
  831. def parse_restart_spec(restart_config):
  832. if not restart_config:
  833. return None
  834. parts = restart_config.split(':')
  835. if len(parts) > 2:
  836. raise ConfigError("Restart %s has incorrect format, should be "
  837. "mode[:max_retry]" % restart_config)
  838. if len(parts) == 2:
  839. name, max_retry_count = parts
  840. else:
  841. name, = parts
  842. max_retry_count = 0
  843. return {'Name': name, 'MaximumRetryCount': int(max_retry_count)}
  844. # Extra hosts
  845. def build_extra_hosts(extra_hosts_config):
  846. if not extra_hosts_config:
  847. return {}
  848. if isinstance(extra_hosts_config, list):
  849. extra_hosts_dict = {}
  850. for extra_hosts_line in extra_hosts_config:
  851. if not isinstance(extra_hosts_line, six.string_types):
  852. raise ConfigError(
  853. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  854. extra_hosts_config
  855. )
  856. host, ip = extra_hosts_line.split(':')
  857. extra_hosts_dict.update({host.strip(): ip.strip()})
  858. extra_hosts_config = extra_hosts_dict
  859. if isinstance(extra_hosts_config, dict):
  860. return extra_hosts_config
  861. raise ConfigError(
  862. "extra_hosts_config \"%s\" must be either a list of strings or a string->string mapping," %
  863. extra_hosts_config
  864. )