service.py 29 KB

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