From c729d5c0b053eb7762426b78682fc0eeca033e81 Mon Sep 17 00:00:00 2001 From: xudan Date: Tue, 27 Feb 2018 01:54:02 -0500 Subject: Bugfix: Dovetail tool will crash when hosts.yaml file with incorrect format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit If the hosts.yaml file is like, — hosts_info: 192.168.141.101: it will raise an exception, File "/usr/local/lib/python2.7/dist-packages/dovetail/utils/dovetail_utils.py", line 227, in add_hosts_info names=hostnames) File "/usr/local/lib/python2.7/dist-packages/python_hosts/hosts.py", line 54, in _init_ raise Exception('Address and Name(s) must be specified.') Exception: Address and Name(s) must be specified. If the hosts.yaml file is empty, it will crash with, File "/usr/local/lib/python2.7/dist-packages/dovetail/container.py", line 174, in create if hosts_yaml['hosts_info']: TypeError: 'NoneType' object has no attribute '_getitem_' JIRA: DOVETAIL-621 Change-Id: I547928e514b3294c048379459c07df89879fbb03 Signed-off-by: xudan --- dovetail/utils/dovetail_utils.py | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) (limited to 'dovetail/utils') diff --git a/dovetail/utils/dovetail_utils.py b/dovetail/utils/dovetail_utils.py index 97186da0..2c16ca71 100644 --- a/dovetail/utils/dovetail_utils.py +++ b/dovetail/utils/dovetail_utils.py @@ -222,9 +222,12 @@ def check_docker_version(logger=None): def add_hosts_info(ip, hostnames): hosts = python_hosts.Hosts(path='/etc/hosts') + filtered_hostnames = [hostname for hostname in hostnames if hostname] + if not ip or not filtered_hostnames: + return new_entry = python_hosts.HostsEntry(entry_type='ipv4', address=ip, - names=hostnames) + names=filtered_hostnames) hosts.add([new_entry]) hosts.write() @@ -346,3 +349,33 @@ def check_cacert_file(cacert, logger=None): .format(dt_cfg.dovetail_config['config_dir'])) return False return True + + +def get_hosts_info(logger=None): + hosts_config = "" + hosts_config_file = os.path.join(dt_cfg.dovetail_config['config_dir'], + 'hosts.yaml') + if not os.path.isfile(hosts_config_file): + return hosts_config + with open(hosts_config_file) as f: + hosts_yaml = yaml.safe_load(f) + if not hosts_yaml: + logger.debug("File {} is empty.".format(hosts_config_file)) + return hosts_config + try: + if not hosts_yaml['hosts_info']: + return hosts_config + for ip, hostnames in hosts_yaml['hosts_info'].iteritems(): + if not hostnames: + continue + add_hosts_info(ip, hostnames) + names_str = ' '.join(hostname for hostname in hostnames + if hostname) + if not names_str: + continue + hosts_config += ' --add-host=\'{}\':{} '.format(names_str, ip) + logger.debug('Get hosts info {}:{}.'.format(ip, names_str)) + except KeyError as e: + logger.error("There is no key {} in file {}" + .format(e, hosts_config_file)) + return hosts_config -- cgit 1.2.3-korg