service.py 30 KB

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