service.py 27 KB

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