config.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import codecs
  4. import functools
  5. import logging
  6. import operator
  7. import os
  8. import string
  9. import sys
  10. from collections import namedtuple
  11. import six
  12. import yaml
  13. from cached_property import cached_property
  14. from ..const import COMPOSEFILE_VERSIONS
  15. from .errors import CircularReference
  16. from .errors import ComposeFileNotFound
  17. from .errors import ConfigurationError
  18. from .interpolation import interpolate_environment_variables
  19. from .sort_services import get_service_name_from_net
  20. from .sort_services import sort_service_dicts
  21. from .types import parse_extra_hosts
  22. from .types import parse_restart_spec
  23. from .types import VolumeFromSpec
  24. from .types import VolumeSpec
  25. from .validation import validate_against_fields_schema
  26. from .validation import validate_against_service_schema
  27. from .validation import validate_depends_on
  28. from .validation import validate_extends_file_path
  29. from .validation import validate_top_level_object
  30. from .validation import validate_top_level_service_objects
  31. from .validation import validate_ulimits
  32. DOCKER_CONFIG_KEYS = [
  33. 'cap_add',
  34. 'cap_drop',
  35. 'cgroup_parent',
  36. 'command',
  37. 'cpu_quota',
  38. 'cpu_shares',
  39. 'cpuset',
  40. 'detach',
  41. 'devices',
  42. 'dns',
  43. 'dns_search',
  44. 'domainname',
  45. 'entrypoint',
  46. 'env_file',
  47. 'environment',
  48. 'extra_hosts',
  49. 'hostname',
  50. 'image',
  51. 'ipc',
  52. 'labels',
  53. 'links',
  54. 'mac_address',
  55. 'mem_limit',
  56. 'memswap_limit',
  57. 'net',
  58. 'pid',
  59. 'ports',
  60. 'privileged',
  61. 'read_only',
  62. 'restart',
  63. 'security_opt',
  64. 'stdin_open',
  65. 'stop_signal',
  66. 'tty',
  67. 'user',
  68. 'volume_driver',
  69. 'volumes',
  70. 'volumes_from',
  71. 'working_dir',
  72. ]
  73. ALLOWED_KEYS = DOCKER_CONFIG_KEYS + [
  74. 'build',
  75. 'container_name',
  76. 'dockerfile',
  77. 'expose',
  78. 'external_links',
  79. 'logging',
  80. ]
  81. DOCKER_VALID_URL_PREFIXES = (
  82. 'http://',
  83. 'https://',
  84. 'git://',
  85. 'github.com/',
  86. 'git@',
  87. )
  88. SUPPORTED_FILENAMES = [
  89. 'docker-compose.yml',
  90. 'docker-compose.yaml',
  91. ]
  92. DEFAULT_OVERRIDE_FILENAME = 'docker-compose.override.yml'
  93. log = logging.getLogger(__name__)
  94. class ConfigDetails(namedtuple('_ConfigDetails', 'working_dir config_files')):
  95. """
  96. :param working_dir: the directory to use for relative paths in the config
  97. :type working_dir: string
  98. :param config_files: list of configuration files to load
  99. :type config_files: list of :class:`ConfigFile`
  100. """
  101. class ConfigFile(namedtuple('_ConfigFile', 'filename config')):
  102. """
  103. :param filename: filename of the config file
  104. :type filename: string
  105. :param config: contents of the config file
  106. :type config: :class:`dict`
  107. """
  108. @classmethod
  109. def from_filename(cls, filename):
  110. return cls(filename, load_yaml(filename))
  111. @cached_property
  112. def version(self):
  113. if self.config is None:
  114. return 1
  115. version = self.config.get('version', 1)
  116. if isinstance(version, dict):
  117. log.warn("Unexpected type for field 'version', in file {} assuming "
  118. "version is the name of a service, and defaulting to "
  119. "Compose file version 1".format(self.filename))
  120. return 1
  121. return version
  122. def get_service_dicts(self):
  123. return self.config if self.version == 1 else self.config.get('services', {})
  124. def get_volumes(self):
  125. return {} if self.version == 1 else self.config.get('volumes', {})
  126. def get_networks(self):
  127. return {} if self.version == 1 else self.config.get('networks', {})
  128. class Config(namedtuple('_Config', 'version services volumes networks')):
  129. """
  130. :param version: configuration version
  131. :type version: int
  132. :param services: List of service description dictionaries
  133. :type services: :class:`list`
  134. :param volumes: Dictionary mapping volume names to description dictionaries
  135. :type volumes: :class:`dict`
  136. :param networks: Dictionary mapping network names to description dictionaries
  137. :type networks: :class:`dict`
  138. """
  139. class ServiceConfig(namedtuple('_ServiceConfig', 'working_dir filename name config')):
  140. @classmethod
  141. def with_abs_paths(cls, working_dir, filename, name, config):
  142. if not working_dir:
  143. raise ValueError("No working_dir for ServiceConfig.")
  144. return cls(
  145. os.path.abspath(working_dir),
  146. os.path.abspath(filename) if filename else filename,
  147. name,
  148. config)
  149. def find(base_dir, filenames):
  150. if filenames == ['-']:
  151. return ConfigDetails(
  152. os.getcwd(),
  153. [ConfigFile(None, yaml.safe_load(sys.stdin))])
  154. if filenames:
  155. filenames = [os.path.join(base_dir, f) for f in filenames]
  156. else:
  157. filenames = get_default_config_files(base_dir)
  158. log.debug("Using configuration files: {}".format(",".join(filenames)))
  159. return ConfigDetails(
  160. os.path.dirname(filenames[0]),
  161. [ConfigFile.from_filename(f) for f in filenames])
  162. def validate_config_version(config_files):
  163. main_file = config_files[0]
  164. validate_top_level_object(main_file)
  165. for next_file in config_files[1:]:
  166. validate_top_level_object(next_file)
  167. if main_file.version != next_file.version:
  168. raise ConfigurationError(
  169. "Version mismatch: file {0} specifies version {1} but "
  170. "extension file {2} uses version {3}".format(
  171. main_file.filename,
  172. main_file.version,
  173. next_file.filename,
  174. next_file.version))
  175. if main_file.version not in COMPOSEFILE_VERSIONS:
  176. raise ConfigurationError(
  177. 'Invalid Compose file version: {0}'.format(main_file.version))
  178. def get_default_config_files(base_dir):
  179. (candidates, path) = find_candidates_in_parent_dirs(SUPPORTED_FILENAMES, base_dir)
  180. if not candidates:
  181. raise ComposeFileNotFound(SUPPORTED_FILENAMES)
  182. winner = candidates[0]
  183. if len(candidates) > 1:
  184. log.warn("Found multiple config files with supported names: %s", ", ".join(candidates))
  185. log.warn("Using %s\n", winner)
  186. return [os.path.join(path, winner)] + get_default_override_file(path)
  187. def get_default_override_file(path):
  188. override_filename = os.path.join(path, DEFAULT_OVERRIDE_FILENAME)
  189. return [override_filename] if os.path.exists(override_filename) else []
  190. def find_candidates_in_parent_dirs(filenames, path):
  191. """
  192. Given a directory path to start, looks for filenames in the
  193. directory, and then each parent directory successively,
  194. until found.
  195. Returns tuple (candidates, path).
  196. """
  197. candidates = [filename for filename in filenames
  198. if os.path.exists(os.path.join(path, filename))]
  199. if not candidates:
  200. parent_dir = os.path.join(path, '..')
  201. if os.path.abspath(parent_dir) != os.path.abspath(path):
  202. return find_candidates_in_parent_dirs(filenames, parent_dir)
  203. return (candidates, path)
  204. def load(config_details):
  205. """Load the configuration from a working directory and a list of
  206. configuration files. Files are loaded in order, and merged on top
  207. of each other to create the final configuration.
  208. Return a fully interpolated, extended and validated configuration.
  209. """
  210. validate_config_version(config_details.config_files)
  211. processed_files = [
  212. process_config_file(config_file)
  213. for config_file in config_details.config_files
  214. ]
  215. config_details = config_details._replace(config_files=processed_files)
  216. main_file = config_details.config_files[0]
  217. volumes = load_mapping(config_details.config_files, 'get_volumes', 'Volume')
  218. networks = load_mapping(config_details.config_files, 'get_networks', 'Network')
  219. service_dicts = load_services(
  220. config_details.working_dir,
  221. main_file,
  222. [file.get_service_dicts() for file in config_details.config_files])
  223. return Config(main_file.version, service_dicts, volumes, networks)
  224. def load_mapping(config_files, get_func, entity_type):
  225. mapping = {}
  226. for config_file in config_files:
  227. for name, config in getattr(config_file, get_func)().items():
  228. mapping[name] = config or {}
  229. if not config:
  230. continue
  231. external = config.get('external')
  232. if external:
  233. if len(config.keys()) > 1:
  234. raise ConfigurationError(
  235. '{} {} declared as external but specifies'
  236. ' additional attributes ({}). '.format(
  237. entity_type,
  238. name,
  239. ', '.join([k for k in config.keys() if k != 'external'])
  240. )
  241. )
  242. if isinstance(external, dict):
  243. config['external_name'] = external.get('name')
  244. else:
  245. config['external_name'] = name
  246. mapping[name] = config
  247. return mapping
  248. def load_services(working_dir, config_file, service_configs):
  249. def build_service(service_name, service_dict, service_names):
  250. service_config = ServiceConfig.with_abs_paths(
  251. working_dir,
  252. config_file.filename,
  253. service_name,
  254. service_dict)
  255. resolver = ServiceExtendsResolver(service_config, config_file)
  256. service_dict = process_service(resolver.run())
  257. service_config = service_config._replace(config=service_dict)
  258. validate_service(service_config, service_names, config_file.version)
  259. service_dict = finalize_service(
  260. service_config,
  261. service_names,
  262. config_file.version)
  263. return service_dict
  264. def build_services(service_config):
  265. service_names = service_config.keys()
  266. return sort_service_dicts([
  267. build_service(name, service_dict, service_names)
  268. for name, service_dict in service_config.items()
  269. ])
  270. def merge_services(base, override):
  271. all_service_names = set(base) | set(override)
  272. return {
  273. name: merge_service_dicts_from_files(
  274. base.get(name, {}),
  275. override.get(name, {}),
  276. config_file.version)
  277. for name in all_service_names
  278. }
  279. service_config = service_configs[0]
  280. for next_config in service_configs[1:]:
  281. service_config = merge_services(service_config, next_config)
  282. return build_services(service_config)
  283. def process_config_file(config_file, service_name=None):
  284. service_dicts = config_file.get_service_dicts()
  285. validate_top_level_service_objects(config_file.filename, service_dicts)
  286. interpolated_config = interpolate_environment_variables(service_dicts, 'service')
  287. if config_file.version == 2:
  288. processed_config = dict(config_file.config)
  289. processed_config['services'] = interpolated_config
  290. processed_config['volumes'] = interpolate_environment_variables(
  291. config_file.get_volumes(), 'volume')
  292. processed_config['networks'] = interpolate_environment_variables(
  293. config_file.get_networks(), 'network')
  294. if config_file.version == 1:
  295. processed_config = interpolated_config
  296. config_file = config_file._replace(config=processed_config)
  297. validate_against_fields_schema(config_file)
  298. if service_name and service_name not in processed_config:
  299. raise ConfigurationError(
  300. "Cannot extend service '{}' in {}: Service not found".format(
  301. service_name, config_file.filename))
  302. return config_file
  303. class ServiceExtendsResolver(object):
  304. def __init__(self, service_config, config_file, already_seen=None):
  305. self.service_config = service_config
  306. self.working_dir = service_config.working_dir
  307. self.already_seen = already_seen or []
  308. self.config_file = config_file
  309. @property
  310. def signature(self):
  311. return self.service_config.filename, self.service_config.name
  312. def detect_cycle(self):
  313. if self.signature in self.already_seen:
  314. raise CircularReference(self.already_seen + [self.signature])
  315. def run(self):
  316. self.detect_cycle()
  317. if 'extends' in self.service_config.config:
  318. service_dict = self.resolve_extends(*self.validate_and_construct_extends())
  319. return self.service_config._replace(config=service_dict)
  320. return self.service_config
  321. def validate_and_construct_extends(self):
  322. extends = self.service_config.config['extends']
  323. if not isinstance(extends, dict):
  324. extends = {'service': extends}
  325. config_path = self.get_extended_config_path(extends)
  326. service_name = extends['service']
  327. extends_file = ConfigFile.from_filename(config_path)
  328. validate_config_version([self.config_file, extends_file])
  329. extended_file = process_config_file(
  330. extends_file,
  331. service_name=service_name)
  332. service_config = extended_file.config[service_name]
  333. return config_path, service_config, service_name
  334. def resolve_extends(self, extended_config_path, service_dict, service_name):
  335. resolver = ServiceExtendsResolver(
  336. ServiceConfig.with_abs_paths(
  337. os.path.dirname(extended_config_path),
  338. extended_config_path,
  339. service_name,
  340. service_dict),
  341. self.config_file,
  342. already_seen=self.already_seen + [self.signature])
  343. service_config = resolver.run()
  344. other_service_dict = process_service(service_config)
  345. validate_extended_service_dict(
  346. other_service_dict,
  347. extended_config_path,
  348. service_name)
  349. return merge_service_dicts(
  350. other_service_dict,
  351. self.service_config.config,
  352. self.config_file.version)
  353. def get_extended_config_path(self, extends_options):
  354. """Service we are extending either has a value for 'file' set, which we
  355. need to obtain a full path too or we are extending from a service
  356. defined in our own file.
  357. """
  358. filename = self.service_config.filename
  359. validate_extends_file_path(
  360. self.service_config.name,
  361. extends_options,
  362. filename)
  363. if 'file' in extends_options:
  364. return expand_path(self.working_dir, extends_options['file'])
  365. return filename
  366. def resolve_environment(service_dict):
  367. """Unpack any environment variables from an env_file, if set.
  368. Interpolate environment values if set.
  369. """
  370. env = {}
  371. for env_file in service_dict.get('env_file', []):
  372. env.update(env_vars_from_file(env_file))
  373. env.update(parse_environment(service_dict.get('environment')))
  374. return dict(resolve_env_var(k, v) for k, v in six.iteritems(env))
  375. def resolve_build_args(build):
  376. args = parse_build_arguments(build.get('args'))
  377. return dict(resolve_env_var(k, v) for k, v in six.iteritems(args))
  378. def validate_extended_service_dict(service_dict, filename, service):
  379. error_prefix = "Cannot extend service '%s' in %s:" % (service, filename)
  380. if 'links' in service_dict:
  381. raise ConfigurationError(
  382. "%s services with 'links' cannot be extended" % error_prefix)
  383. if 'volumes_from' in service_dict:
  384. raise ConfigurationError(
  385. "%s services with 'volumes_from' cannot be extended" % error_prefix)
  386. if 'net' in service_dict:
  387. if get_service_name_from_net(service_dict['net']) is not None:
  388. raise ConfigurationError(
  389. "%s services with 'net: container' cannot be extended" % error_prefix)
  390. if 'depends_on' in service_dict:
  391. raise ConfigurationError(
  392. "%s services with 'depends_on' cannot be extended" % error_prefix)
  393. def validate_service(service_config, service_names, version):
  394. service_dict, service_name = service_config.config, service_config.name
  395. validate_against_service_schema(service_dict, service_name, version)
  396. validate_paths(service_dict)
  397. validate_ulimits(service_config)
  398. validate_depends_on(service_config, service_names)
  399. if not service_dict.get('image') and has_uppercase(service_name):
  400. raise ConfigurationError(
  401. "Service '{name}' contains uppercase characters which are not valid "
  402. "as part of an image name. Either use a lowercase service name or "
  403. "use the `image` field to set a custom name for the service image."
  404. .format(name=service_name))
  405. def process_service(service_config):
  406. working_dir = service_config.working_dir
  407. service_dict = dict(service_config.config)
  408. if 'env_file' in service_dict:
  409. service_dict['env_file'] = [
  410. expand_path(working_dir, path)
  411. for path in to_list(service_dict['env_file'])
  412. ]
  413. if 'build' in service_dict:
  414. if isinstance(service_dict['build'], six.string_types):
  415. service_dict['build'] = resolve_build_path(working_dir, service_dict['build'])
  416. elif isinstance(service_dict['build'], dict) and 'context' in service_dict['build']:
  417. path = service_dict['build']['context']
  418. service_dict['build']['context'] = resolve_build_path(working_dir, path)
  419. if 'volumes' in service_dict and service_dict.get('volume_driver') is None:
  420. service_dict['volumes'] = resolve_volume_paths(working_dir, service_dict)
  421. if 'labels' in service_dict:
  422. service_dict['labels'] = parse_labels(service_dict['labels'])
  423. if 'extra_hosts' in service_dict:
  424. service_dict['extra_hosts'] = parse_extra_hosts(service_dict['extra_hosts'])
  425. for field in ['dns', 'dns_search']:
  426. if field in service_dict:
  427. service_dict[field] = to_list(service_dict[field])
  428. return service_dict
  429. def finalize_service(service_config, service_names, version):
  430. service_dict = dict(service_config.config)
  431. if 'environment' in service_dict or 'env_file' in service_dict:
  432. service_dict['environment'] = resolve_environment(service_dict)
  433. service_dict.pop('env_file', None)
  434. if 'volumes_from' in service_dict:
  435. service_dict['volumes_from'] = [
  436. VolumeFromSpec.parse(vf, service_names, version)
  437. for vf in service_dict['volumes_from']
  438. ]
  439. if 'volumes' in service_dict:
  440. service_dict['volumes'] = [
  441. VolumeSpec.parse(v) for v in service_dict['volumes']]
  442. if 'restart' in service_dict:
  443. service_dict['restart'] = parse_restart_spec(service_dict['restart'])
  444. normalize_build(service_dict, service_config.working_dir)
  445. service_dict['name'] = service_config.name
  446. return normalize_v1_service_format(service_dict)
  447. def normalize_v1_service_format(service_dict):
  448. if 'log_driver' in service_dict or 'log_opt' in service_dict:
  449. if 'logging' not in service_dict:
  450. service_dict['logging'] = {}
  451. if 'log_driver' in service_dict:
  452. service_dict['logging']['driver'] = service_dict['log_driver']
  453. del service_dict['log_driver']
  454. if 'log_opt' in service_dict:
  455. service_dict['logging']['options'] = service_dict['log_opt']
  456. del service_dict['log_opt']
  457. if 'dockerfile' in service_dict:
  458. service_dict['build'] = service_dict.get('build', {})
  459. service_dict['build'].update({
  460. 'dockerfile': service_dict.pop('dockerfile')
  461. })
  462. return service_dict
  463. def merge_service_dicts_from_files(base, override, version):
  464. """When merging services from multiple files we need to merge the `extends`
  465. field. This is not handled by `merge_service_dicts()` which is used to
  466. perform the `extends`.
  467. """
  468. new_service = merge_service_dicts(base, override, version)
  469. if 'extends' in override:
  470. new_service['extends'] = override['extends']
  471. elif 'extends' in base:
  472. new_service['extends'] = base['extends']
  473. return new_service
  474. def merge_service_dicts(base, override, version):
  475. d = {}
  476. def merge_field(field, merge_func, default=None):
  477. if field in base or field in override:
  478. d[field] = merge_func(
  479. base.get(field, default),
  480. override.get(field, default))
  481. def merge_mapping(mapping, parse_func):
  482. if mapping in base or mapping in override:
  483. merged = parse_func(base.get(mapping, None))
  484. merged.update(parse_func(override.get(mapping, None)))
  485. d[mapping] = merged
  486. merge_mapping('environment', parse_environment)
  487. merge_mapping('labels', parse_labels)
  488. merge_mapping('ulimits', parse_ulimits)
  489. for field in ['volumes', 'devices']:
  490. merge_field(field, merge_path_mappings)
  491. for field in ['ports', 'expose', 'external_links']:
  492. merge_field(field, operator.add, default=[])
  493. for field in ['dns', 'dns_search', 'env_file']:
  494. merge_field(field, merge_list_or_string)
  495. for field in set(ALLOWED_KEYS) - set(d):
  496. if field in base or field in override:
  497. d[field] = override.get(field, base.get(field))
  498. if version == 1:
  499. legacy_v1_merge_image_or_build(d, base, override)
  500. else:
  501. merge_build(d, base, override)
  502. return d
  503. def merge_build(output, base, override):
  504. build = {}
  505. if 'build' in base:
  506. if isinstance(base['build'], six.string_types):
  507. build['context'] = base['build']
  508. else:
  509. build.update(base['build'])
  510. if 'build' in override:
  511. if isinstance(override['build'], six.string_types):
  512. build['context'] = override['build']
  513. else:
  514. build.update(override['build'])
  515. if build:
  516. output['build'] = build
  517. def legacy_v1_merge_image_or_build(output, base, override):
  518. output.pop('image', None)
  519. output.pop('build', None)
  520. if 'image' in override:
  521. output['image'] = override['image']
  522. elif 'build' in override:
  523. output['build'] = override['build']
  524. elif 'image' in base:
  525. output['image'] = base['image']
  526. elif 'build' in base:
  527. output['build'] = base['build']
  528. def merge_environment(base, override):
  529. env = parse_environment(base)
  530. env.update(parse_environment(override))
  531. return env
  532. def split_env(env):
  533. if isinstance(env, six.binary_type):
  534. env = env.decode('utf-8', 'replace')
  535. if '=' in env:
  536. return env.split('=', 1)
  537. else:
  538. return env, None
  539. def split_label(label):
  540. if '=' in label:
  541. return label.split('=', 1)
  542. else:
  543. return label, ''
  544. def parse_dict_or_list(split_func, type_name, arguments):
  545. if not arguments:
  546. return {}
  547. if isinstance(arguments, list):
  548. return dict(split_func(e) for e in arguments)
  549. if isinstance(arguments, dict):
  550. return dict(arguments)
  551. raise ConfigurationError(
  552. "%s \"%s\" must be a list or mapping," %
  553. (type_name, arguments)
  554. )
  555. parse_build_arguments = functools.partial(parse_dict_or_list, split_env, 'build arguments')
  556. parse_environment = functools.partial(parse_dict_or_list, split_env, 'environment')
  557. parse_labels = functools.partial(parse_dict_or_list, split_label, 'labels')
  558. def parse_ulimits(ulimits):
  559. if not ulimits:
  560. return {}
  561. if isinstance(ulimits, dict):
  562. return dict(ulimits)
  563. def resolve_env_var(key, val):
  564. if val is not None:
  565. return key, val
  566. elif key in os.environ:
  567. return key, os.environ[key]
  568. else:
  569. return key, ''
  570. def env_vars_from_file(filename):
  571. """
  572. Read in a line delimited file of environment variables.
  573. """
  574. if not os.path.exists(filename):
  575. raise ConfigurationError("Couldn't find env file: %s" % filename)
  576. env = {}
  577. for line in codecs.open(filename, 'r', 'utf-8'):
  578. line = line.strip()
  579. if line and not line.startswith('#'):
  580. k, v = split_env(line)
  581. env[k] = v
  582. return env
  583. def resolve_volume_paths(working_dir, service_dict):
  584. return [
  585. resolve_volume_path(working_dir, volume)
  586. for volume in service_dict['volumes']
  587. ]
  588. def resolve_volume_path(working_dir, volume):
  589. container_path, host_path = split_path_mapping(volume)
  590. if host_path is not None:
  591. if host_path.startswith('.'):
  592. host_path = expand_path(working_dir, host_path)
  593. host_path = os.path.expanduser(host_path)
  594. return u"{}:{}".format(host_path, container_path)
  595. else:
  596. return container_path
  597. def normalize_build(service_dict, working_dir):
  598. if 'build' in service_dict:
  599. build = {}
  600. # Shortcut where specifying a string is treated as the build context
  601. if isinstance(service_dict['build'], six.string_types):
  602. build['context'] = service_dict.pop('build')
  603. else:
  604. build.update(service_dict['build'])
  605. if 'args' in build:
  606. build['args'] = resolve_build_args(build)
  607. service_dict['build'] = build
  608. def resolve_build_path(working_dir, build_path):
  609. if is_url(build_path):
  610. return build_path
  611. return expand_path(working_dir, build_path)
  612. def is_url(build_path):
  613. return build_path.startswith(DOCKER_VALID_URL_PREFIXES)
  614. def validate_paths(service_dict):
  615. if 'build' in service_dict:
  616. build = service_dict.get('build', {})
  617. if isinstance(build, six.string_types):
  618. build_path = build
  619. elif isinstance(build, dict) and 'context' in build:
  620. build_path = build['context']
  621. if (
  622. not is_url(build_path) and
  623. (not os.path.exists(build_path) or not os.access(build_path, os.R_OK))
  624. ):
  625. raise ConfigurationError(
  626. "build path %s either does not exist, is not accessible, "
  627. "or is not a valid URL." % build_path)
  628. def merge_path_mappings(base, override):
  629. d = dict_from_path_mappings(base)
  630. d.update(dict_from_path_mappings(override))
  631. return path_mappings_from_dict(d)
  632. def dict_from_path_mappings(path_mappings):
  633. if path_mappings:
  634. return dict(split_path_mapping(v) for v in path_mappings)
  635. else:
  636. return {}
  637. def path_mappings_from_dict(d):
  638. return [join_path_mapping(v) for v in d.items()]
  639. def split_path_mapping(volume_path):
  640. """
  641. Ascertain if the volume_path contains a host path as well as a container
  642. path. Using splitdrive so windows absolute paths won't cause issues with
  643. splitting on ':'.
  644. """
  645. # splitdrive has limitations when it comes to relative paths, so when it's
  646. # relative, handle special case to set the drive to ''
  647. if volume_path.startswith('.') or volume_path.startswith('~'):
  648. drive, volume_config = '', volume_path
  649. else:
  650. drive, volume_config = os.path.splitdrive(volume_path)
  651. if ':' in volume_config:
  652. (host, container) = volume_config.split(':', 1)
  653. return (container, drive + host)
  654. else:
  655. return (volume_path, None)
  656. def join_path_mapping(pair):
  657. (container, host) = pair
  658. if host is None:
  659. return container
  660. else:
  661. return ":".join((host, container))
  662. def expand_path(working_dir, path):
  663. return os.path.abspath(os.path.join(working_dir, os.path.expanduser(path)))
  664. def merge_list_or_string(base, override):
  665. return to_list(base) + to_list(override)
  666. def to_list(value):
  667. if value is None:
  668. return []
  669. elif isinstance(value, six.string_types):
  670. return [value]
  671. else:
  672. return value
  673. def has_uppercase(name):
  674. return any(char in string.ascii_uppercase for char in name)
  675. def load_yaml(filename):
  676. try:
  677. with open(filename, 'r') as fh:
  678. return yaml.safe_load(fh)
  679. except (IOError, yaml.YAMLError) as e:
  680. error_name = getattr(e, '__module__', '') + '.' + e.__class__.__name__
  681. raise ConfigurationError(u"{}: {}".format(error_name, e))