config.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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. 'secrets',
  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. 'configs',
  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. if isinstance(service_dict['build'], six.string_types):
  581. service_dict['build'] = resolve_build_path(working_dir, service_dict['build'])
  582. elif isinstance(service_dict['build'], dict):
  583. if 'context' in service_dict['build']:
  584. path = service_dict['build']['context']
  585. service_dict['build']['context'] = resolve_build_path(working_dir, path)
  586. if 'labels' in service_dict['build']:
  587. service_dict['build']['labels'] = parse_labels(service_dict['build']['labels'])
  588. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  589. service_dict['volumes'] = resolve_volume_paths(working_dir, service_dict)
  590. if 'sysctls' in service_dict:
  591. service_dict['sysctls'] = build_string_dict(parse_sysctls(service_dict['sysctls']))
  592. service_dict = process_depends_on(service_dict)
  593. for field in ['dns', 'dns_search', 'tmpfs']:
  594. if field in service_dict:
  595. service_dict[field] = to_list(service_dict[field])
  596. service_dict = process_blkio_config(process_ports(
  597. process_healthcheck(service_dict, service_config.name)
  598. ))
  599. return service_dict
  600. def process_ports(service_dict):
  601. if 'ports' not in service_dict:
  602. return service_dict
  603. ports = []
  604. for port_definition in service_dict['ports']:
  605. if isinstance(port_definition, ServicePort):
  606. ports.append(port_definition)
  607. else:
  608. ports.extend(ServicePort.parse(port_definition))
  609. service_dict['ports'] = ports
  610. return service_dict
  611. def process_depends_on(service_dict):
  612. if 'depends_on' in service_dict and not isinstance(service_dict['depends_on'], dict):
  613. service_dict['depends_on'] = dict([
  614. (svc, {'condition': 'service_started'}) for svc in service_dict['depends_on']
  615. ])
  616. return service_dict
  617. def process_blkio_config(service_dict):
  618. if not service_dict.get('blkio_config'):
  619. return service_dict
  620. for field in ['device_read_bps', 'device_write_bps']:
  621. if field in service_dict['blkio_config']:
  622. for v in service_dict['blkio_config'].get(field, []):
  623. rate = v.get('rate', 0)
  624. v['rate'] = parse_bytes(rate)
  625. if v['rate'] is None:
  626. raise ConfigurationError('Invalid format for bytes value: "{}"'.format(rate))
  627. for field in ['device_read_iops', 'device_write_iops']:
  628. if field in service_dict['blkio_config']:
  629. for v in service_dict['blkio_config'].get(field, []):
  630. try:
  631. v['rate'] = int(v.get('rate', 0))
  632. except ValueError:
  633. raise ConfigurationError(
  634. 'Invalid IOPS value: "{}". Must be a positive integer.'.format(v.get('rate'))
  635. )
  636. return service_dict
  637. def process_healthcheck(service_dict, service_name):
  638. if 'healthcheck' not in service_dict:
  639. return service_dict
  640. hc = {}
  641. raw = service_dict['healthcheck']
  642. if raw.get('disable'):
  643. if len(raw) > 1:
  644. raise ConfigurationError(
  645. 'Service "{}" defines an invalid healthcheck: '
  646. '"disable: true" cannot be combined with other options'
  647. .format(service_name))
  648. hc['test'] = ['NONE']
  649. elif 'test' in raw:
  650. hc['test'] = raw['test']
  651. for field in ['interval', 'timeout', 'start_period']:
  652. if field in raw:
  653. if not isinstance(raw[field], six.integer_types):
  654. hc[field] = parse_nanoseconds_int(raw[field])
  655. else: # Conversion has been done previously
  656. hc[field] = raw[field]
  657. if 'retries' in raw:
  658. hc['retries'] = raw['retries']
  659. service_dict['healthcheck'] = hc
  660. return service_dict
  661. def finalize_service(service_config, service_names, version, environment):
  662. service_dict = dict(service_config.config)
  663. if 'environment' in service_dict or 'env_file' in service_dict:
  664. service_dict['environment'] = resolve_environment(service_dict, environment)
  665. service_dict.pop('env_file', None)
  666. if 'volumes_from' in service_dict:
  667. service_dict['volumes_from'] = [
  668. VolumeFromSpec.parse(vf, service_names, version)
  669. for vf in service_dict['volumes_from']
  670. ]
  671. if 'volumes' in service_dict:
  672. service_dict['volumes'] = [
  673. VolumeSpec.parse(
  674. v, environment.get_boolean('COMPOSE_CONVERT_WINDOWS_PATHS')
  675. ) for v in service_dict['volumes']
  676. ]
  677. if 'net' in service_dict:
  678. network_mode = service_dict.pop('net')
  679. container_name = get_container_name_from_network_mode(network_mode)
  680. if container_name and container_name in service_names:
  681. service_dict['network_mode'] = 'service:{}'.format(container_name)
  682. else:
  683. service_dict['network_mode'] = network_mode
  684. if 'networks' in service_dict:
  685. service_dict['networks'] = parse_networks(service_dict['networks'])
  686. if 'restart' in service_dict:
  687. service_dict['restart'] = parse_restart_spec(service_dict['restart'])
  688. if 'secrets' in service_dict:
  689. service_dict['secrets'] = [
  690. types.ServiceSecret.parse(s) for s in service_dict['secrets']
  691. ]
  692. if 'configs' in service_dict:
  693. service_dict['configs'] = [
  694. types.ServiceConfig.parse(c) for c in service_dict['configs']
  695. ]
  696. normalize_build(service_dict, service_config.working_dir, environment)
  697. service_dict['name'] = service_config.name
  698. return normalize_v1_service_format(service_dict)
  699. def normalize_v1_service_format(service_dict):
  700. if 'log_driver' in service_dict or 'log_opt' in service_dict:
  701. if 'logging' not in service_dict:
  702. service_dict['logging'] = {}
  703. if 'log_driver' in service_dict:
  704. service_dict['logging']['driver'] = service_dict['log_driver']
  705. del service_dict['log_driver']
  706. if 'log_opt' in service_dict:
  707. service_dict['logging']['options'] = service_dict['log_opt']
  708. del service_dict['log_opt']
  709. if 'dockerfile' in service_dict:
  710. service_dict['build'] = service_dict.get('build', {})
  711. service_dict['build'].update({
  712. 'dockerfile': service_dict.pop('dockerfile')
  713. })
  714. return service_dict
  715. def merge_service_dicts_from_files(base, override, version):
  716. """When merging services from multiple files we need to merge the `extends`
  717. field. This is not handled by `merge_service_dicts()` which is used to
  718. perform the `extends`.
  719. """
  720. new_service = merge_service_dicts(base, override, version)
  721. if 'extends' in override:
  722. new_service['extends'] = override['extends']
  723. elif 'extends' in base:
  724. new_service['extends'] = base['extends']
  725. return new_service
  726. class MergeDict(dict):
  727. """A dict-like object responsible for merging two dicts into one."""
  728. def __init__(self, base, override):
  729. self.base = base
  730. self.override = override
  731. def needs_merge(self, field):
  732. return field in self.base or field in self.override
  733. def merge_field(self, field, merge_func, default=None):
  734. if not self.needs_merge(field):
  735. return
  736. self[field] = merge_func(
  737. self.base.get(field, default),
  738. self.override.get(field, default))
  739. def merge_mapping(self, field, parse_func):
  740. if not self.needs_merge(field):
  741. return
  742. self[field] = parse_func(self.base.get(field))
  743. self[field].update(parse_func(self.override.get(field)))
  744. def merge_sequence(self, field, parse_func):
  745. def parse_sequence_func(seq):
  746. return to_mapping((parse_func(item) for item in seq), 'merge_field')
  747. if not self.needs_merge(field):
  748. return
  749. merged = parse_sequence_func(self.base.get(field, []))
  750. merged.update(parse_sequence_func(self.override.get(field, [])))
  751. self[field] = [item.repr() for item in sorted(merged.values())]
  752. def merge_scalar(self, field):
  753. if self.needs_merge(field):
  754. self[field] = self.override.get(field, self.base.get(field))
  755. def merge_service_dicts(base, override, version):
  756. md = MergeDict(base, override)
  757. md.merge_mapping('environment', parse_environment)
  758. md.merge_mapping('labels', parse_labels)
  759. md.merge_mapping('ulimits', parse_flat_dict)
  760. md.merge_mapping('networks', parse_networks)
  761. md.merge_mapping('sysctls', parse_sysctls)
  762. md.merge_mapping('depends_on', parse_depends_on)
  763. md.merge_sequence('links', ServiceLink.parse)
  764. md.merge_sequence('secrets', types.ServiceSecret.parse)
  765. md.merge_sequence('configs', types.ServiceConfig.parse)
  766. md.merge_mapping('deploy', parse_deploy)
  767. md.merge_mapping('extra_hosts', parse_extra_hosts)
  768. for field in ['volumes', 'devices']:
  769. md.merge_field(field, merge_path_mappings)
  770. for field in [
  771. 'cap_add', 'cap_drop', 'expose', 'external_links',
  772. 'security_opt', 'volumes_from',
  773. ]:
  774. md.merge_field(field, merge_unique_items_lists, default=[])
  775. for field in ['dns', 'dns_search', 'env_file', 'tmpfs']:
  776. md.merge_field(field, merge_list_or_string)
  777. md.merge_field('logging', merge_logging, default={})
  778. merge_ports(md, base, override)
  779. md.merge_field('blkio_config', merge_blkio_config, default={})
  780. md.merge_field('healthcheck', merge_healthchecks, default={})
  781. for field in set(ALLOWED_KEYS) - set(md):
  782. md.merge_scalar(field)
  783. if version == V1:
  784. legacy_v1_merge_image_or_build(md, base, override)
  785. elif md.needs_merge('build'):
  786. md['build'] = merge_build(md, base, override)
  787. return dict(md)
  788. def merge_unique_items_lists(base, override):
  789. override = [str(o) for o in override]
  790. base = [str(b) for b in base]
  791. return sorted(set().union(base, override))
  792. def merge_healthchecks(base, override):
  793. if override.get('disabled') is True:
  794. return override
  795. result = base.copy()
  796. result.update(override)
  797. return result
  798. def merge_ports(md, base, override):
  799. def parse_sequence_func(seq):
  800. acc = []
  801. for item in seq:
  802. acc.extend(ServicePort.parse(item))
  803. return to_mapping(acc, 'merge_field')
  804. field = 'ports'
  805. if not md.needs_merge(field):
  806. return
  807. merged = parse_sequence_func(md.base.get(field, []))
  808. merged.update(parse_sequence_func(md.override.get(field, [])))
  809. md[field] = [item for item in sorted(merged.values(), key=lambda x: x.target)]
  810. def merge_build(output, base, override):
  811. def to_dict(service):
  812. build_config = service.get('build', {})
  813. if isinstance(build_config, six.string_types):
  814. return {'context': build_config}
  815. return build_config
  816. md = MergeDict(to_dict(base), to_dict(override))
  817. md.merge_scalar('context')
  818. md.merge_scalar('dockerfile')
  819. md.merge_scalar('network')
  820. md.merge_scalar('target')
  821. md.merge_scalar('shm_size')
  822. md.merge_mapping('args', parse_build_arguments)
  823. md.merge_field('cache_from', merge_unique_items_lists, default=[])
  824. md.merge_mapping('labels', parse_labels)
  825. return dict(md)
  826. def merge_blkio_config(base, override):
  827. md = MergeDict(base, override)
  828. md.merge_scalar('weight')
  829. def merge_blkio_limits(base, override):
  830. index = dict((b['path'], b) for b in base)
  831. for o in override:
  832. index[o['path']] = o
  833. return sorted(list(index.values()), key=lambda x: x['path'])
  834. for field in [
  835. "device_read_bps", "device_read_iops", "device_write_bps",
  836. "device_write_iops", "weight_device",
  837. ]:
  838. md.merge_field(field, merge_blkio_limits, default=[])
  839. return dict(md)
  840. def merge_logging(base, override):
  841. md = MergeDict(base, override)
  842. md.merge_scalar('driver')
  843. if md.get('driver') == base.get('driver') or base.get('driver') is None:
  844. md.merge_mapping('options', lambda m: m or {})
  845. elif override.get('options'):
  846. md['options'] = override.get('options', {})
  847. return dict(md)
  848. def legacy_v1_merge_image_or_build(output, base, override):
  849. output.pop('image', None)
  850. output.pop('build', None)
  851. if 'image' in override:
  852. output['image'] = override['image']
  853. elif 'build' in override:
  854. output['build'] = override['build']
  855. elif 'image' in base:
  856. output['image'] = base['image']
  857. elif 'build' in base:
  858. output['build'] = base['build']
  859. def merge_environment(base, override):
  860. env = parse_environment(base)
  861. env.update(parse_environment(override))
  862. return env
  863. def split_kv(kvpair):
  864. if '=' in kvpair:
  865. return kvpair.split('=', 1)
  866. else:
  867. return kvpair, ''
  868. def parse_dict_or_list(split_func, type_name, arguments):
  869. if not arguments:
  870. return {}
  871. if isinstance(arguments, list):
  872. return dict(split_func(e) for e in arguments)
  873. if isinstance(arguments, dict):
  874. return dict(arguments)
  875. raise ConfigurationError(
  876. "%s \"%s\" must be a list or mapping," %
  877. (type_name, arguments)
  878. )
  879. parse_build_arguments = functools.partial(parse_dict_or_list, split_env, 'build arguments')
  880. parse_environment = functools.partial(parse_dict_or_list, split_env, 'environment')
  881. parse_labels = functools.partial(parse_dict_or_list, split_kv, 'labels')
  882. parse_networks = functools.partial(parse_dict_or_list, lambda k: (k, None), 'networks')
  883. parse_sysctls = functools.partial(parse_dict_or_list, split_kv, 'sysctls')
  884. parse_depends_on = functools.partial(
  885. parse_dict_or_list, lambda k: (k, {'condition': 'service_started'}), 'depends_on'
  886. )
  887. parse_deploy = functools.partial(parse_dict_or_list, split_kv, 'deploy')
  888. def parse_flat_dict(d):
  889. if not d:
  890. return {}
  891. if isinstance(d, dict):
  892. return dict(d)
  893. raise ConfigurationError("Invalid type: expected mapping")
  894. def resolve_env_var(key, val, environment):
  895. if val is not None:
  896. return key, val
  897. elif environment and key in environment:
  898. return key, environment[key]
  899. else:
  900. return key, None
  901. def resolve_volume_paths(working_dir, service_dict):
  902. return [
  903. resolve_volume_path(working_dir, volume)
  904. for volume in service_dict['volumes']
  905. ]
  906. def resolve_volume_path(working_dir, volume):
  907. mount_params = None
  908. if isinstance(volume, dict):
  909. container_path = volume.get('target')
  910. host_path = volume.get('source')
  911. mode = None
  912. if host_path:
  913. if volume.get('read_only'):
  914. mode = 'ro'
  915. if volume.get('volume', {}).get('nocopy'):
  916. mode = 'nocopy'
  917. mount_params = (host_path, mode)
  918. else:
  919. container_path, mount_params = split_path_mapping(volume)
  920. if mount_params is not None:
  921. host_path, mode = mount_params
  922. if host_path is None:
  923. return container_path
  924. if host_path.startswith('.'):
  925. host_path = expand_path(working_dir, host_path)
  926. host_path = os.path.expanduser(host_path)
  927. return u"{}:{}{}".format(host_path, container_path, (':' + mode if mode else ''))
  928. return container_path
  929. def normalize_build(service_dict, working_dir, environment):
  930. if 'build' in service_dict:
  931. build = {}
  932. # Shortcut where specifying a string is treated as the build context
  933. if isinstance(service_dict['build'], six.string_types):
  934. build['context'] = service_dict.pop('build')
  935. else:
  936. build.update(service_dict['build'])
  937. if 'args' in build:
  938. build['args'] = build_string_dict(
  939. resolve_build_args(build.get('args'), environment)
  940. )
  941. service_dict['build'] = build
  942. def resolve_build_path(working_dir, build_path):
  943. if is_url(build_path):
  944. return build_path
  945. return expand_path(working_dir, build_path)
  946. def is_url(build_path):
  947. return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
  948. def validate_paths(service_dict):
  949. if 'build' in service_dict:
  950. build = service_dict.get('build', {})
  951. if isinstance(build, six.string_types):
  952. build_path = build
  953. elif isinstance(build, dict) and 'context' in build:
  954. build_path = build['context']
  955. else:
  956. # We have a build section but no context, so nothing to validate
  957. return
  958. if (
  959. not is_url(build_path) and
  960. (not os.path.exists(build_path) or not os.access(build_path, os.R_OK))
  961. ):
  962. raise ConfigurationError(
  963. "build path %s either does not exist, is not accessible, "
  964. "or is not a valid URL." % build_path)
  965. def merge_path_mappings(base, override):
  966. d = dict_from_path_mappings(base)
  967. d.update(dict_from_path_mappings(override))
  968. return path_mappings_from_dict(d)
  969. def dict_from_path_mappings(path_mappings):
  970. if path_mappings:
  971. return dict(split_path_mapping(v) for v in path_mappings)
  972. else:
  973. return {}
  974. def path_mappings_from_dict(d):
  975. return [join_path_mapping(v) for v in sorted(d.items())]
  976. def split_path_mapping(volume_path):
  977. """
  978. Ascertain if the volume_path contains a host path as well as a container
  979. path. Using splitdrive so windows absolute paths won't cause issues with
  980. splitting on ':'.
  981. """
  982. if isinstance(volume_path, dict):
  983. return (volume_path.get('target'), volume_path)
  984. drive, volume_config = splitdrive(volume_path)
  985. if ':' in volume_config:
  986. (host, container) = volume_config.split(':', 1)
  987. container_drive, container_path = splitdrive(container)
  988. mode = None
  989. if ':' in container_path:
  990. container_path, mode = container_path.rsplit(':', 1)
  991. return (container_drive + container_path, (drive + host, mode))
  992. else:
  993. return (volume_path, None)
  994. def join_path_mapping(pair):
  995. (container, host) = pair
  996. if isinstance(host, dict):
  997. return host
  998. elif host is None:
  999. return container
  1000. else:
  1001. host, mode = host
  1002. result = ":".join((host, container))
  1003. if mode:
  1004. result += ":" + mode
  1005. return result
  1006. def expand_path(working_dir, path):
  1007. return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
  1008. def merge_list_or_string(base, override):
  1009. return to_list(base) + to_list(override)
  1010. def to_list(value):
  1011. if value is None:
  1012. return []
  1013. elif isinstance(value, six.string_types):
  1014. return [value]
  1015. else:
  1016. return value
  1017. def to_mapping(sequence, key_field):
  1018. return {getattr(item, key_field): item for item in sequence}
  1019. def has_uppercase(name):
  1020. return any(char in string.ascii_uppercase for char in name)
  1021. def load_yaml(filename):
  1022. try:
  1023. with open(filename, 'r') as fh:
  1024. return yaml.safe_load(fh)
  1025. except (IOError, yaml.YAMLError) as e:
  1026. error_name = getattr(e, '__module__', '') + '.' + e.__class__.__name__
  1027. raise ConfigurationError(u"{}: {}".format(error_name, e))