1
0

service.py 31 KB

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