config.py 24 KB

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