service.py 30 KB

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