config.py 42 KB

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