config.py 42 KB

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