service.py 33 KB

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