service.py 33 KB

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