config.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import functools
  4. import logging
  5. import os
  6. import string
  7. import sys
  8. from collections import namedtuple
  9. import six
  10. import yaml
  11. from cached_property import cached_property
  12. from . import types
  13. from .. import const
  14. from ..const import COMPOSEFILE_V1 as V1
  15. from ..utils import build_string_dict
  16. from ..utils import parse_bytes
  17. from ..utils import parse_nanoseconds_int
  18. from ..utils import splitdrive
  19. from ..version import ComposeVersion
  20. from .environment import env_vars_from_file
  21. from .environment import Environment
  22. from .environment import split_env
  23. from .errors import CircularReference
  24. from .errors import ComposeFileNotFound
  25. from .errors import ConfigurationError
  26. from .errors import DuplicateOverrideFileFound
  27. from .errors import VERSION_EXPLANATION
  28. from .interpolation import interpolate_environment_variables
  29. from .sort_services import get_container_name_from_network_mode
  30. from .sort_services import get_service_name_from_network_mode
  31. from .sort_services import sort_service_dicts
  32. from .types import parse_extra_hosts
  33. from .types import parse_restart_spec
  34. from .types import ServiceLink
  35. from .types import ServicePort
  36. from .types import VolumeFromSpec
  37. from .types import VolumeSpec
  38. from .validation import match_named_volumes
  39. from .validation import validate_against_config_schema
  40. from .validation import validate_config_section
  41. from .validation import validate_cpu
  42. from .validation import validate_depends_on
  43. from .validation import validate_extends_file_path
  44. from .validation import validate_links
  45. from .validation import validate_network_mode
  46. from .validation import validate_pid_mode
  47. from .validation import validate_service_constraints
  48. from .validation import validate_top_level_object
  49. from .validation import validate_ulimits
  50. DOCKER_CONFIG_KEYS = [
  51. 'cap_add',
  52. 'cap_drop',
  53. 'cgroup_parent',
  54. 'command',
  55. 'cpu_count',
  56. 'cpu_percent',
  57. 'cpu_quota',
  58. 'cpu_shares',
  59. 'cpus',
  60. 'cpuset',
  61. 'detach',
  62. 'devices',
  63. 'dns',
  64. 'dns_search',
  65. 'dns_opt',
  66. 'domainname',
  67. 'entrypoint',
  68. 'env_file',
  69. 'environment',
  70. 'extra_hosts',
  71. 'group_add',
  72. 'hostname',
  73. 'healthcheck',
  74. 'image',
  75. 'ipc',
  76. 'labels',
  77. 'links',
  78. 'mac_address',
  79. 'mem_limit',
  80. 'mem_reservation',
  81. 'memswap_limit',
  82. 'mem_swappiness',
  83. 'net',
  84. 'oom_score_adj',
  85. 'pid',
  86. 'ports',
  87. 'privileged',
  88. 'read_only',
  89. 'restart',
  90. 'secrets',
  91. 'security_opt',
  92. 'shm_size',
  93. 'pids_limit',
  94. 'stdin_open',
  95. 'stop_signal',
  96. 'sysctls',
  97. 'tty',
  98. 'user',
  99. 'userns_mode',
  100. 'volume_driver',
  101. 'volumes',
  102. 'volumes_from',
  103. 'working_dir',
  104. ]
  105. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  106. 'blkio_config',
  107. 'build',
  108. 'container_name',
  109. 'credential_spec',
  110. 'dockerfile',
  111. 'log_driver',
  112. 'log_opt',
  113. 'logging',
  114. 'network_mode',
  115. 'init',
  116. 'scale',
  117. ]
  118. DOCKER_VALID_URL_PREFIXES = (
  119. 'http://',
  120. 'https://',
  121. 'git://',
  122. 'github.com/',
  123. 'git@',
  124. )
  125. SUPPORTED_FILENAMES = [
  126. 'docker-compose.yml',
  127. 'docker-compose.yaml',
  128. ]
  129. DEFAULT_OVERRIDE_FILENAMES = ('docker-compose.override.yml', 'docker-compose.override.yaml')
  130. log = logging.getLogger(__name__)
  131. class ConfigDetails(namedtuple('_ConfigDetails', 'working_dir config_files environment')):
  132. """
  133. :param working_dir: the directory to use for relative paths in the config
  134. :type working_dir: string
  135. :param config_files: list of configuration files to load
  136. :type config_files: list of :class:`ConfigFile`
  137. :param environment: computed environment values for this project
  138. :type environment: :class:`environment.Environment`
  139. """
  140. def __new__(cls, working_dir, config_files, environment=None):
  141. if environment is None:
  142. environment = Environment.from_env_file(working_dir)
  143. return super(ConfigDetails, cls).__new__(
  144. cls, working_dir, config_files, environment
  145. )
  146. class ConfigFile(namedtuple('_ConfigFile', 'filename config')):
  147. """
  148. :param filename: filename of the config file
  149. :type filename: string
  150. :param config: contents of the config file
  151. :type config: :class:`dict`
  152. """
  153. @classmethod
  154. def from_filename(cls, filename):
  155. return cls(filename, load_yaml(filename))
  156. @cached_property
  157. def version(self):
  158. if 'version' not in self.config:
  159. return V1
  160. version = self.config['version']
  161. if isinstance(version, dict):
  162. log.warn('Unexpected type for "version" key in "{}". Assuming '
  163. '"version" is the name of a service, and defaulting to '
  164. 'Compose file version 1.'.format(self.filename))
  165. return V1
  166. if not isinstance(version, six.string_types):
  167. raise ConfigurationError(
  168. 'Version in "{}" is invalid - it should be a string.'
  169. .format(self.filename))
  170. if version == '1':
  171. raise ConfigurationError(
  172. 'Version in "{}" is invalid. {}'
  173. .format(self.filename, VERSION_EXPLANATION)
  174. )
  175. if version == '2':
  176. return const.COMPOSEFILE_V2_0
  177. if version == '3':
  178. return const.COMPOSEFILE_V3_0
  179. return ComposeVersion(version)
  180. def get_service(self, name):
  181. return self.get_service_dicts()[name]
  182. def get_service_dicts(self):
  183. return self.config if self.version == V1 else self.config.get('services', {})
  184. def get_volumes(self):
  185. return {} if self.version == V1 else self.config.get('volumes', {})
  186. def get_networks(self):
  187. return {} if self.version == V1 else self.config.get('networks', {})
  188. def get_secrets(self):
  189. return {} if self.version < const.COMPOSEFILE_V3_1 else self.config.get('secrets', {})
  190. def get_configs(self):
  191. return {} if self.version < const.COMPOSEFILE_V3_3 else self.config.get('configs', {})
  192. class Config(namedtuple('_Config', 'version services volumes networks secrets configs')):
  193. """
  194. :param version: configuration version
  195. :type version: int
  196. :param services: List of service description dictionaries
  197. :type services: :class:`list`
  198. :param volumes: Dictionary mapping volume names to description dictionaries
  199. :type volumes: :class:`dict`
  200. :param networks: Dictionary mapping network names to description dictionaries
  201. :type networks: :class:`dict`
  202. :param secrets: Dictionary mapping secret names to description dictionaries
  203. :type secrets: :class:`dict`
  204. :param configs: Dictionary mapping config names to description dictionaries
  205. :type configs: :class:`dict`
  206. """
  207. class ServiceConfig(namedtuple('_ServiceConfig', 'working_dir filename name config')):
  208. @classmethod
  209. def with_abs_paths(cls, working_dir, filename, name, config):
  210. if not working_dir:
  211. raise ValueError("No working_dir for ServiceConfig.")
  212. return cls(
  213. os.path.abspath(working_dir),
  214. os.path.abspath(filename) if filename else filename,
  215. name,
  216. config)
  217. def find(base_dir, filenames, environment, override_dir=None):
  218. if filenames == ['-']:
  219. return ConfigDetails(
  220. os.path.abspath(override_dir) if override_dir else os.getcwd(),
  221. [ConfigFile(None, yaml.safe_load(sys.stdin))],
  222. environment
  223. )
  224. if filenames:
  225. filenames = [os.path.join(base_dir, f) for f in filenames]
  226. else:
  227. filenames = get_default_config_files(base_dir)
  228. log.debug("Using configuration files: {}".format(",".join(filenames)))
  229. return ConfigDetails(
  230. override_dir if override_dir else os.path.dirname(filenames[0]),
  231. [ConfigFile.from_filename(f) for f in filenames],
  232. environment
  233. )
  234. def validate_config_version(config_files):
  235. main_file = config_files[0]
  236. validate_top_level_object(main_file)
  237. for next_file in config_files[1:]:
  238. validate_top_level_object(next_file)
  239. if main_file.version != next_file.version:
  240. raise ConfigurationError(
  241. "Version mismatch: file {0} specifies version {1} but "
  242. "extension file {2} uses version {3}".format(
  243. main_file.filename,
  244. main_file.version,
  245. next_file.filename,
  246. next_file.version))
  247. def get_default_config_files(base_dir):
  248. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  249. if not candidates:
  250. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  251. winner = candidates[0]
  252. if len(candidates) > 1:
  253. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  254. log.warn("Using %s\n", winner)
  255. return [os.path.join(path, winner)] + get_default_override_file(path)
  256. def get_default_override_file(path):
  257. override_files_in_path = [os.path.join(path, override_filename) for override_filename
  258. in DEFAULT_OVERRIDE_FILENAMES
  259. if os.path.exists(os.path.join(path, override_filename))]
  260. if len(override_files_in_path) > 1:
  261. raise DuplicateOverrideFileFound(override_files_in_path)
  262. return override_files_in_path
  263. def find_candidates_in_parent_dirs(filenames, path):
  264. """
  265. Given a directory path to start, looks for filenames in the
  266. directory, and then each parent directory successively,
  267. until found.
  268. Returns tuple (candidates, path).
  269. """
  270. candidates = [filename for filename in filenames
  271. if os.path.exists(os.path.join(path, filename))]
  272. if not candidates:
  273. parent_dir = os.path.join(path, '..')
  274. if os.path.abspath(parent_dir) != os.path.abspath(path):
  275. return find_candidates_in_parent_dirs(filenames, parent_dir)
  276. return (candidates, path)
  277. def check_swarm_only_config(service_dicts):
  278. warning_template = (
  279. "Some services ({services}) use the '{key}' key, which will be ignored. "
  280. "Compose does not support '{key}' configuration - use "
  281. "`docker stack deploy` to deploy to a swarm."
  282. )
  283. def check_swarm_only_key(service_dicts, key):
  284. services = [s for s in service_dicts if s.get(key)]
  285. if services:
  286. log.warn(
  287. warning_template.format(
  288. services=", ".join(sorted(s['name'] for s in services)),
  289. key=key
  290. )
  291. )
  292. check_swarm_only_key(service_dicts, 'deploy')
  293. check_swarm_only_key(service_dicts, 'credential_spec')
  294. check_swarm_only_key(service_dicts, 'configs')
  295. def load(config_details):
  296. """Load the configuration from a working directory and a list of
  297. configuration files. Files are loaded in order, and merged on top
  298. of each other to create the final configuration.
  299. Return a fully interpolated, extended and validated configuration.
  300. """
  301. validate_config_version(config_details.config_files)
  302. processed_files = [
  303. process_config_file(config_file, config_details.environment)
  304. for config_file in config_details.config_files
  305. ]
  306. config_details = config_details._replace(config_files=processed_files)
  307. main_file = config_details.config_files[0]
  308. volumes = load_mapping(
  309. config_details.config_files, 'get_volumes', 'Volume'
  310. )
  311. networks = load_mapping(
  312. config_details.config_files, 'get_networks', 'Network'
  313. )
  314. secrets = load_mapping(
  315. config_details.config_files, 'get_secrets', 'Secret', config_details.working_dir
  316. )
  317. configs = load_mapping(
  318. config_details.config_files, 'get_configs', 'Config', config_details.working_dir
  319. )
  320. service_dicts = load_services(config_details, main_file)
  321. if main_file.version != V1:
  322. for service_dict in service_dicts:
  323. match_named_volumes(service_dict, volumes)
  324. check_swarm_only_config(service_dicts)
  325. return Config(main_file.version, service_dicts, volumes, networks, secrets, configs)
  326. def load_mapping(config_files, get_func, entity_type, working_dir=None):
  327. mapping = {}
  328. for config_file in config_files:
  329. for name, config in getattr(config_file, get_func)().items():
  330. mapping[name] = config or {}
  331. if not config:
  332. continue
  333. external = config.get('external')
  334. if external:
  335. name_field = 'name' if entity_type == 'Volume' else 'external_name'
  336. validate_external(entity_type, name, config)
  337. if isinstance(external, dict):
  338. config[name_field] = external.get('name')
  339. elif not config.get('name'):
  340. config[name_field] = name
  341. if 'driver_opts' in config:
  342. config['driver_opts'] = build_string_dict(
  343. config['driver_opts']
  344. )
  345. if 'labels' in config:
  346. config['labels'] = parse_labels(config['labels'])
  347. if 'file' in config:
  348. config['file'] = expand_path(working_dir, config['file'])
  349. return mapping
  350. def validate_external(entity_type, name, config):
  351. if len(config.keys()) <= 1:
  352. return
  353. raise ConfigurationError(
  354. "{} {} declared as external but specifies additional attributes "
  355. "({}).".format(
  356. entity_type, name, ', '.join(k for k in config if k != 'external')))
  357. def load_services(config_details, config_file):
  358. def build_service(service_name, service_dict, service_names):
  359. service_config = ServiceConfig.with_abs_paths(
  360. config_details.working_dir,
  361. config_file.filename,
  362. service_name,
  363. service_dict)
  364. resolver = ServiceExtendsResolver(
  365. service_config, config_file, environment=config_details.environment
  366. )
  367. service_dict = process_service(resolver.run())
  368. service_config = service_config._replace(config=service_dict)
  369. validate_service(service_config, service_names, config_file)
  370. service_dict = finalize_service(
  371. service_config,
  372. service_names,
  373. config_file.version,
  374. config_details.environment)
  375. return service_dict
  376. def build_services(service_config):
  377. service_names = service_config.keys()
  378. return sort_service_dicts([
  379. build_service(name, service_dict, service_names)
  380. for name, service_dict in service_config.items()
  381. ])
  382. def merge_services(base, override):
  383. all_service_names = set(base) | set(override)
  384. return {
  385. name: merge_service_dicts_from_files(
  386. base.get(name, {}),
  387. override.get(name, {}),
  388. config_file.version)
  389. for name in all_service_names
  390. }
  391. service_configs = [
  392. file.get_service_dicts() for file in config_details.config_files
  393. ]
  394. service_config = service_configs[0]
  395. for next_config in service_configs[1:]:
  396. service_config = merge_services(service_config, next_config)
  397. return build_services(service_config)
  398. def interpolate_config_section(config_file, config, section, environment):
  399. validate_config_section(config_file.filename, config, section)
  400. return interpolate_environment_variables(
  401. config_file.version,
  402. config,
  403. section,
  404. environment
  405. )
  406. def process_config_file(config_file, environment, service_name=None):
  407. services = interpolate_config_section(
  408. config_file,
  409. config_file.get_service_dicts(),
  410. 'service',
  411. environment)
  412. if config_file.version > V1:
  413. processed_config = dict(config_file.config)
  414. processed_config['services'] = services
  415. processed_config['volumes'] = interpolate_config_section(
  416. config_file,
  417. config_file.get_volumes(),
  418. 'volume',
  419. environment)
  420. processed_config['networks'] = interpolate_config_section(
  421. config_file,
  422. config_file.get_networks(),
  423. 'network',
  424. environment)
  425. if config_file.version >= const.COMPOSEFILE_V3_1:
  426. processed_config['secrets'] = interpolate_config_section(
  427. config_file,
  428. config_file.get_secrets(),
  429. 'secrets',
  430. environment)
  431. if config_file.version >= const.COMPOSEFILE_V3_3:
  432. processed_config['configs'] = interpolate_config_section(
  433. config_file,
  434. config_file.get_configs(),
  435. 'configs',
  436. environment
  437. )
  438. else:
  439. processed_config = services
  440. config_file = config_file._replace(config=processed_config)
  441. validate_against_config_schema(config_file)
  442. if service_name and service_name not in services:
  443. raise ConfigurationError(
  444. "Cannot extend service '{}' in {}: Service not found".format(
  445. service_name, config_file.filename))
  446. return config_file
  447. class ServiceExtendsResolver(object):
  448. def __init__(self, service_config, config_file, environment, already_seen=None):
  449. self.service_config = service_config
  450. self.working_dir = service_config.working_dir
  451. self.already_seen = already_seen or []
  452. self.config_file = config_file
  453. self.environment = environment
  454. @property
  455. def signature(self):
  456. return self.service_config.filename, self.service_config.name
  457. def detect_cycle(self):
  458. if self.signature in self.already_seen:
  459. raise CircularReference(self.already_seen + [self.signature])
  460. def run(self):
  461. self.detect_cycle()
  462. if 'extends' in self.service_config.config:
  463. service_dict = self.resolve_extends(*self.validate_and_construct_extends())
  464. return self.service_config._replace(config=service_dict)
  465. return self.service_config
  466. def validate_and_construct_extends(self):
  467. extends = self.service_config.config['extends']
  468. if not isinstance(extends, dict):
  469. extends = {'service': extends}
  470. config_path = self.get_extended_config_path(extends)
  471. service_name = extends['service']
  472. if config_path == self.config_file.filename:
  473. try:
  474. service_config = self.config_file.get_service(service_name)
  475. except KeyError:
  476. raise ConfigurationError(
  477. "Cannot extend service '{}' in {}: Service not found".format(
  478. service_name, config_path)
  479. )
  480. else:
  481. extends_file = ConfigFile.from_filename(config_path)
  482. validate_config_version([self.config_file, extends_file])
  483. extended_file = process_config_file(
  484. extends_file, self.environment, service_name=service_name
  485. )
  486. service_config = extended_file.get_service(service_name)
  487. return config_path, service_config, service_name
  488. def resolve_extends(self, extended_config_path, service_dict, service_name):
  489. resolver = ServiceExtendsResolver(
  490. ServiceConfig.with_abs_paths(
  491. os.path.dirname(extended_config_path),
  492. extended_config_path,
  493. service_name,
  494. service_dict),
  495. self.config_file,
  496. already_seen=self.already_seen + [self.signature],
  497. environment=self.environment
  498. )
  499. service_config = resolver.run()
  500. other_service_dict = process_service(service_config)
  501. validate_extended_service_dict(
  502. other_service_dict,
  503. extended_config_path,
  504. service_name)
  505. return merge_service_dicts(
  506. other_service_dict,
  507. self.service_config.config,
  508. self.config_file.version)
  509. def get_extended_config_path(self, extends_options):
  510. """Service we are extending either has a value for 'file' set, which we
  511. need to obtain a full path too or we are extending from a service
  512. defined in our own file.
  513. """
  514. filename = self.service_config.filename
  515. validate_extends_file_path(
  516. self.service_config.name,
  517. extends_options,
  518. filename)
  519. if 'file' in extends_options:
  520. return expand_path(self.working_dir, extends_options['file'])
  521. return filename
  522. def resolve_environment(service_dict, environment=None):
  523. """Unpack any environment variables from an env_file, if set.
  524. Interpolate environment values if set.
  525. """
  526. env = {}
  527. for env_file in service_dict.get('env_file', []):
  528. env.update(env_vars_from_file(env_file))
  529. env.update(parse_environment(service_dict.get('environment')))
  530. return dict(resolve_env_var(k, v, environment) for k, v in six.iteritems(env))
  531. def resolve_build_args(buildargs, environment):
  532. args = parse_build_arguments(buildargs)
  533. return dict(resolve_env_var(k, v, environment) for k, v in six.iteritems(args))
  534. def validate_extended_service_dict(service_dict, filename, service):
  535. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  536. if 'links' in service_dict:
  537. raise ConfigurationError(
  538. "%s services with 'links' cannot be extended" % error_prefix)
  539. if 'volumes_from' in service_dict:
  540. raise ConfigurationError(
  541. "%s services with 'volumes_from' cannot be extended" % error_prefix)
  542. if 'net' in service_dict:
  543. if get_container_name_from_network_mode(service_dict['net']):
  544. raise ConfigurationError(
  545. "%s services with 'net: container' cannot be extended" % error_prefix)
  546. if 'network_mode' in service_dict:
  547. if get_service_name_from_network_mode(service_dict['network_mode']):
  548. raise ConfigurationError(
  549. "%s services with 'network_mode: service' cannot be extended" % error_prefix)
  550. if 'depends_on' in service_dict:
  551. raise ConfigurationError(
  552. "%s services with 'depends_on' cannot be extended" % error_prefix)
  553. def validate_service(service_config, service_names, config_file):
  554. service_dict, service_name = service_config.config, service_config.name
  555. validate_service_constraints(service_dict, service_name, config_file)
  556. validate_paths(service_dict)
  557. validate_cpu(service_config)
  558. validate_ulimits(service_config)
  559. validate_network_mode(service_config, service_names)
  560. validate_pid_mode(service_config, service_names)
  561. validate_depends_on(service_config, service_names)
  562. validate_links(service_config, service_names)
  563. if not service_dict.get('image') and has_uppercase(service_name):
  564. raise ConfigurationError(
  565. "Service '{name}' contains uppercase characters which are not valid "
  566. "as part of an image name. Either use a lowercase service name or "
  567. "use the `image` field to set a custom name for the service image."
  568. .format(name=service_name))
  569. def process_service(service_config):
  570. working_dir = service_config.working_dir
  571. service_dict = dict(service_config.config)
  572. if 'env_file' in service_dict:
  573. service_dict['env_file'] = [
  574. expand_path(working_dir, path)
  575. for path in to_list(service_dict['env_file'])
  576. ]
  577. if 'build' in service_dict:
  578. if isinstance(service_dict['build'], six.string_types):
  579. service_dict['build'] = resolve_build_path(working_dir, service_dict['build'])
  580. elif isinstance(service_dict['build'], dict) and 'context' in service_dict['build']:
  581. path = service_dict['build']['context']
  582. service_dict['build']['context'] = resolve_build_path(working_dir, path)
  583. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  584. service_dict['volumes'] = resolve_volume_paths(working_dir, service_dict)
  585. if 'labels' in service_dict:
  586. service_dict['labels'] = parse_labels(service_dict['labels'])
  587. if 'sysctls' in service_dict:
  588. service_dict['sysctls'] = build_string_dict(parse_sysctls(service_dict['sysctls']))
  589. service_dict = process_depends_on(service_dict)
  590. for field in ['dns', 'dns_search', 'tmpfs']:
  591. if field in service_dict:
  592. service_dict[field] = to_list(service_dict[field])
  593. service_dict = process_blkio_config(process_ports(
  594. process_healthcheck(service_dict, service_config.name)
  595. ))
  596. return service_dict
  597. def process_ports(service_dict):
  598. if 'ports' not in service_dict:
  599. return service_dict
  600. ports = []
  601. for port_definition in service_dict['ports']:
  602. if isinstance(port_definition, ServicePort):
  603. ports.append(port_definition)
  604. else:
  605. ports.extend(ServicePort.parse(port_definition))
  606. service_dict['ports'] = ports
  607. return service_dict
  608. def process_depends_on(service_dict):
  609. if 'depends_on' in service_dict and not isinstance(service_dict['depends_on'], dict):
  610. service_dict['depends_on'] = dict([
  611. (svc, {'condition': 'service_started'}) for svc in service_dict['depends_on']
  612. ])
  613. return service_dict
  614. def process_blkio_config(service_dict):
  615. if not service_dict.get('blkio_config'):
  616. return service_dict
  617. for field in ['device_read_bps', 'device_write_bps']:
  618. if field in service_dict['blkio_config']:
  619. for v in service_dict['blkio_config'].get(field, []):
  620. rate = v.get('rate', 0)
  621. v['rate'] = parse_bytes(rate)
  622. if v['rate'] is None:
  623. raise ConfigurationError('Invalid format for bytes value: "{}"'.format(rate))
  624. for field in ['device_read_iops', 'device_write_iops']:
  625. if field in service_dict['blkio_config']:
  626. for v in service_dict['blkio_config'].get(field, []):
  627. try:
  628. v['rate'] = int(v.get('rate', 0))
  629. except ValueError:
  630. raise ConfigurationError(
  631. 'Invalid IOPS value: "{}". Must be a positive integer.'.format(v.get('rate'))
  632. )
  633. return service_dict
  634. def process_healthcheck(service_dict, service_name):
  635. if 'healthcheck' not in service_dict:
  636. return service_dict
  637. hc = {}
  638. raw = service_dict['healthcheck']
  639. if raw.get('disable'):
  640. if len(raw) > 1:
  641. raise ConfigurationError(
  642. 'Service "{}" defines an invalid healthcheck: '
  643. '"disable: true" cannot be combined with other options'
  644. .format(service_name))
  645. hc['test'] = ['NONE']
  646. elif 'test' in raw:
  647. hc['test'] = raw['test']
  648. for field in ['interval', 'timeout', 'start_period']:
  649. if field in raw:
  650. if not isinstance(raw[field], six.integer_types):
  651. hc[field] = parse_nanoseconds_int(raw[field])
  652. else: # Conversion has been done previously
  653. hc[field] = raw[field]
  654. if 'retries' in raw:
  655. hc['retries'] = raw['retries']
  656. service_dict['healthcheck'] = hc
  657. return service_dict
  658. def finalize_service(service_config, service_names, version, environment):
  659. service_dict = dict(service_config.config)
  660. if 'environment' in service_dict or 'env_file' in service_dict:
  661. service_dict['environment'] = resolve_environment(service_dict, environment)
  662. service_dict.pop('env_file', None)
  663. if 'volumes_from' in service_dict:
  664. service_dict['volumes_from'] = [
  665. VolumeFromSpec.parse(vf, service_names, version)
  666. for vf in service_dict['volumes_from']
  667. ]
  668. if 'volumes' in service_dict:
  669. service_dict['volumes'] = [
  670. VolumeSpec.parse(
  671. v, environment.get_boolean('COMPOSE_CONVERT_WINDOWS_PATHS')
  672. ) for v in service_dict['volumes']
  673. ]
  674. if 'net' in service_dict:
  675. network_mode = service_dict.pop('net')
  676. container_name = get_container_name_from_network_mode(network_mode)
  677. if container_name and container_name in service_names:
  678. service_dict['network_mode'] = 'service:{}'.format(container_name)
  679. else:
  680. service_dict['network_mode'] = network_mode
  681. if 'networks' in service_dict:
  682. service_dict['networks'] = parse_networks(service_dict['networks'])
  683. if 'restart' in service_dict:
  684. service_dict['restart'] = parse_restart_spec(service_dict['restart'])
  685. if 'secrets' in service_dict:
  686. service_dict['secrets'] = [
  687. types.ServiceSecret.parse(s) for s in service_dict['secrets']
  688. ]
  689. if 'configs' in service_dict:
  690. service_dict['configs'] = [
  691. types.ServiceConfig.parse(c) for c in service_dict['configs']
  692. ]
  693. normalize_build(service_dict, service_config.working_dir, environment)
  694. service_dict['name'] = service_config.name
  695. return normalize_v1_service_format(service_dict)
  696. def normalize_v1_service_format(service_dict):
  697. if 'log_driver' in service_dict or 'log_opt' in service_dict:
  698. if 'logging' not in service_dict:
  699. service_dict['logging'] = {}
  700. if 'log_driver' in service_dict:
  701. service_dict['logging']['driver'] = service_dict['log_driver']
  702. del service_dict['log_driver']
  703. if 'log_opt' in service_dict:
  704. service_dict['logging']['options'] = service_dict['log_opt']
  705. del service_dict['log_opt']
  706. if 'dockerfile' in service_dict:
  707. service_dict['build'] = service_dict.get('build', {})
  708. service_dict['build'].update({
  709. 'dockerfile': service_dict.pop('dockerfile')
  710. })
  711. return service_dict
  712. def merge_service_dicts_from_files(base, override, version):
  713. """When merging services from multiple files we need to merge the `extends`
  714. field. This is not handled by `merge_service_dicts()` which is used to
  715. perform the `extends`.
  716. """
  717. new_service = merge_service_dicts(base, override, version)
  718. if 'extends' in override:
  719. new_service['extends'] = override['extends']
  720. elif 'extends' in base:
  721. new_service['extends'] = base['extends']
  722. return new_service
  723. class MergeDict(dict):
  724. """A dict-like object responsible for merging two dicts into one."""
  725. def __init__(self, base, override):
  726. self.base = base
  727. self.override = override
  728. def needs_merge(self, field):
  729. return field in self.base or field in self.override
  730. def merge_field(self, field, merge_func, default=None):
  731. if not self.needs_merge(field):
  732. return
  733. self[field] = merge_func(
  734. self.base.get(field, default),
  735. self.override.get(field, default))
  736. def merge_mapping(self, field, parse_func):
  737. if not self.needs_merge(field):
  738. return
  739. self[field] = parse_func(self.base.get(field))
  740. self[field].update(parse_func(self.override.get(field)))
  741. def merge_sequence(self, field, parse_func):
  742. def parse_sequence_func(seq):
  743. return to_mapping((parse_func(item) for item in seq), 'merge_field')
  744. if not self.needs_merge(field):
  745. return
  746. merged = parse_sequence_func(self.base.get(field, []))
  747. merged.update(parse_sequence_func(self.override.get(field, [])))
  748. self[field] = [item.repr() for item in sorted(merged.values())]
  749. def merge_scalar(self, field):
  750. if self.needs_merge(field):
  751. self[field] = self.override.get(field, self.base.get(field))
  752. def merge_service_dicts(base, override, version):
  753. md = MergeDict(base, override)
  754. md.merge_mapping('environment', parse_environment)
  755. md.merge_mapping('labels', parse_labels)
  756. md.merge_mapping('ulimits', parse_flat_dict)
  757. md.merge_mapping('networks', parse_networks)
  758. md.merge_mapping('sysctls', parse_sysctls)
  759. md.merge_mapping('depends_on', parse_depends_on)
  760. md.merge_sequence('links', ServiceLink.parse)
  761. md.merge_sequence('secrets', types.ServiceSecret.parse)
  762. md.merge_sequence('configs', types.ServiceConfig.parse)
  763. md.merge_mapping('deploy', parse_deploy)
  764. md.merge_mapping('extra_hosts', parse_extra_hosts)
  765. for field in ['volumes', 'devices']:
  766. md.merge_field(field, merge_path_mappings)
  767. for field in [
  768. 'cap_add', 'cap_drop', 'expose', 'external_links',
  769. 'security_opt', 'volumes_from',
  770. ]:
  771. md.merge_field(field, merge_unique_items_lists, default=[])
  772. for field in ['dns', 'dns_search', 'env_file', 'tmpfs']:
  773. md.merge_field(field, merge_list_or_string)
  774. md.merge_field('logging', merge_logging, default={})
  775. merge_ports(md, base, override)
  776. md.merge_field('blkio_config', merge_blkio_config, default={})
  777. md.merge_field('healthcheck', merge_healthchecks, default={})
  778. for field in set(ALLOWED_KEYS) - set(md):
  779. md.merge_scalar(field)
  780. if version == V1:
  781. legacy_v1_merge_image_or_build(md, base, override)
  782. elif md.needs_merge('build'):
  783. md['build'] = merge_build(md, base, override)
  784. return dict(md)
  785. def merge_unique_items_lists(base, override):
  786. override = [str(o) for o in override]
  787. base = [str(b) for b in base]
  788. return sorted(set().union(base, override))
  789. def merge_healthchecks(base, override):
  790. if override.get('disabled') is True:
  791. return override
  792. result = base.copy()
  793. result.update(override)
  794. return result
  795. def merge_ports(md, base, override):
  796. def parse_sequence_func(seq):
  797. acc = []
  798. for item in seq:
  799. acc.extend(ServicePort.parse(item))
  800. return to_mapping(acc, 'merge_field')
  801. field = 'ports'
  802. if not md.needs_merge(field):
  803. return
  804. merged = parse_sequence_func(md.base.get(field, []))
  805. merged.update(parse_sequence_func(md.override.get(field, [])))
  806. md[field] = [item for item in sorted(merged.values(), key=lambda x: x.target)]
  807. def merge_build(output, base, override):
  808. def to_dict(service):
  809. build_config = service.get('build', {})
  810. if isinstance(build_config, six.string_types):
  811. return {'context': build_config}
  812. return build_config
  813. md = MergeDict(to_dict(base), to_dict(override))
  814. md.merge_scalar('context')
  815. md.merge_scalar('dockerfile')
  816. md.merge_scalar('network')
  817. md.merge_scalar('target')
  818. md.merge_scalar('shm_size')
  819. md.merge_mapping('args', parse_build_arguments)
  820. md.merge_field('cache_from', merge_unique_items_lists, default=[])
  821. md.merge_mapping('labels', parse_labels)
  822. return dict(md)
  823. def merge_blkio_config(base, override):
  824. md = MergeDict(base, override)
  825. md.merge_scalar('weight')
  826. def merge_blkio_limits(base, override):
  827. index = dict((b['path'], b) for b in base)
  828. for o in override:
  829. index[o['path']] = o
  830. return sorted(list(index.values()), key=lambda x: x['path'])
  831. for field in [
  832. "device_read_bps", "device_read_iops", "device_write_bps",
  833. "device_write_iops", "weight_device",
  834. ]:
  835. md.merge_field(field, merge_blkio_limits, default=[])
  836. return dict(md)
  837. def merge_logging(base, override):
  838. md = MergeDict(base, override)
  839. md.merge_scalar('driver')
  840. if md.get('driver') == base.get('driver') or base.get('driver') is None:
  841. md.merge_mapping('options', lambda m: m or {})
  842. elif override.get('options'):
  843. md['options'] = override.get('options', {})
  844. return dict(md)
  845. def legacy_v1_merge_image_or_build(output, base, override):
  846. output.pop('image', None)
  847. output.pop('build', None)
  848. if 'image' in override:
  849. output['image'] = override['image']
  850. elif 'build' in override:
  851. output['build'] = override['build']
  852. elif 'image' in base:
  853. output['image'] = base['image']
  854. elif 'build' in base:
  855. output['build'] = base['build']
  856. def merge_environment(base, override):
  857. env = parse_environment(base)
  858. env.update(parse_environment(override))
  859. return env
  860. def split_kv(kvpair):
  861. if '=' in kvpair:
  862. return kvpair.split('=', 1)
  863. else:
  864. return kvpair, ''
  865. def parse_dict_or_list(split_func, type_name, arguments):
  866. if not arguments:
  867. return {}
  868. if isinstance(arguments, list):
  869. return dict(split_func(e) for e in arguments)
  870. if isinstance(arguments, dict):
  871. return dict(arguments)
  872. raise ConfigurationError(
  873. "%s \"%s\" must be a list or mapping," %
  874. (type_name, arguments)
  875. )
  876. parse_build_arguments = functools.partial(parse_dict_or_list, split_env, 'build arguments')
  877. parse_environment = functools.partial(parse_dict_or_list, split_env, 'environment')
  878. parse_labels = functools.partial(parse_dict_or_list, split_kv, 'labels')
  879. parse_networks = functools.partial(parse_dict_or_list, lambda k: (k, None), 'networks')
  880. parse_sysctls = functools.partial(parse_dict_or_list, split_kv, 'sysctls')
  881. parse_depends_on = functools.partial(
  882. parse_dict_or_list, lambda k: (k, {'condition': 'service_started'}), 'depends_on'
  883. )
  884. parse_deploy = functools.partial(parse_dict_or_list, split_kv, 'deploy')
  885. def parse_flat_dict(d):
  886. if not d:
  887. return {}
  888. if isinstance(d, dict):
  889. return dict(d)
  890. raise ConfigurationError("Invalid type: expected mapping")
  891. def resolve_env_var(key, val, environment):
  892. if val is not None:
  893. return key, val
  894. elif environment and key in environment:
  895. return key, environment[key]
  896. else:
  897. return key, None
  898. def resolve_volume_paths(working_dir, service_dict):
  899. return [
  900. resolve_volume_path(working_dir, volume)
  901. for volume in service_dict['volumes']
  902. ]
  903. def resolve_volume_path(working_dir, volume):
  904. mount_params = None
  905. if isinstance(volume, dict):
  906. container_path = volume.get('target')
  907. host_path = volume.get('source')
  908. mode = None
  909. if host_path:
  910. if volume.get('read_only'):
  911. mode = 'ro'
  912. if volume.get('volume', {}).get('nocopy'):
  913. mode = 'nocopy'
  914. mount_params = (host_path, mode)
  915. else:
  916. container_path, mount_params = split_path_mapping(volume)
  917. if mount_params is not None:
  918. host_path, mode = mount_params
  919. if host_path is None:
  920. return container_path
  921. if host_path.startswith('.'):
  922. host_path = expand_path(working_dir, host_path)
  923. host_path = os.path.expanduser(host_path)
  924. return u"{}:{}{}".format(host_path, container_path, (':' + mode if mode else ''))
  925. return container_path
  926. def normalize_build(service_dict, working_dir, environment):
  927. if 'build' in service_dict:
  928. build = {}
  929. # Shortcut where specifying a string is treated as the build context
  930. if isinstance(service_dict['build'], six.string_types):
  931. build['context'] = service_dict.pop('build')
  932. else:
  933. build.update(service_dict['build'])
  934. if 'args' in build:
  935. build['args'] = build_string_dict(
  936. resolve_build_args(build.get('args'), environment)
  937. )
  938. service_dict['build'] = build
  939. def resolve_build_path(working_dir, build_path):
  940. if is_url(build_path):
  941. return build_path
  942. return expand_path(working_dir, build_path)
  943. def is_url(build_path):
  944. return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
  945. def validate_paths(service_dict):
  946. if 'build' in service_dict:
  947. build = service_dict.get('build', {})
  948. if isinstance(build, six.string_types):
  949. build_path = build
  950. elif isinstance(build, dict) and 'context' in build:
  951. build_path = build['context']
  952. else:
  953. # We have a build section but no context, so nothing to validate
  954. return
  955. if (
  956. not is_url(build_path) and
  957. (not os.path.exists(build_path) or not os.access(build_path, os.R_OK))
  958. ):
  959. raise ConfigurationError(
  960. "build path %s either does not exist, is not accessible, "
  961. "or is not a valid URL." % build_path)
  962. def merge_path_mappings(base, override):
  963. d = dict_from_path_mappings(base)
  964. d.update(dict_from_path_mappings(override))
  965. return path_mappings_from_dict(d)
  966. def dict_from_path_mappings(path_mappings):
  967. if path_mappings:
  968. return dict(split_path_mapping(v) for v in path_mappings)
  969. else:
  970. return {}
  971. def path_mappings_from_dict(d):
  972. return [join_path_mapping(v) for v in sorted(d.items())]
  973. def split_path_mapping(volume_path):
  974. """
  975. Ascertain if the volume_path contains a host path as well as a container
  976. path. Using splitdrive so windows absolute paths won't cause issues with
  977. splitting on ':'.
  978. """
  979. if isinstance(volume_path, dict):
  980. return (volume_path.get('target'), volume_path)
  981. drive, volume_config = splitdrive(volume_path)
  982. if ':' in volume_config:
  983. (host, container) = volume_config.split(':', 1)
  984. container_drive, container_path = splitdrive(container)
  985. mode = None
  986. if ':' in container_path:
  987. container_path, mode = container_path.rsplit(':', 1)
  988. return (container_drive + container_path, (drive + host, mode))
  989. else:
  990. return (volume_path, None)
  991. def join_path_mapping(pair):
  992. (container, host) = pair
  993. if isinstance(host, dict):
  994. return host
  995. elif host is None:
  996. return container
  997. else:
  998. host, mode = host
  999. result = ":".join((host, container))
  1000. if mode:
  1001. result += ":" + mode
  1002. return result
  1003. def expand_path(working_dir, path):
  1004. return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
  1005. def merge_list_or_string(base, override):
  1006. return to_list(base) + to_list(override)
  1007. def to_list(value):
  1008. if value is None:
  1009. return []
  1010. elif isinstance(value, six.string_types):
  1011. return [value]
  1012. else:
  1013. return value
  1014. def to_mapping(sequence, key_field):
  1015. return {getattr(item, key_field): item for item in sequence}
  1016. def has_uppercase(name):
  1017. return any(char in string.ascii_uppercase for char in name)
  1018. def load_yaml(filename):
  1019. try:
  1020. with open(filename, 'r') as fh:
  1021. return yaml.safe_load(fh)
  1022. except (IOError, yaml.YAMLError) as e:
  1023. error_name = getattr(e, '__module__', '') + '.' + e.__class__.__name__
  1024. raise ConfigurationError(u"{}: {}".format(error_name, e))