service.py 30 KB

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