config.py 42 KB

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