diff --git a/nova/api/openstack/compute/views/servers.py b/nova/api/openstack/compute/views/servers.py index d895c45aec6f..2c60fdeda6d1 100644 --- a/nova/api/openstack/compute/views/servers.py +++ b/nova/api/openstack/compute/views/servers.py @@ -14,8 +14,6 @@ # License for the specific language governing permissions and limitations # under the License. -import hashlib - from oslo_log import log as logging from nova.api.openstack import api_version_request @@ -134,7 +132,7 @@ class ViewBuilder(common.ViewBuilder): "tenant_id": instance.get("project_id") or "", "user_id": instance.get("user_id") or "", "metadata": self._get_metadata(instance), - "hostId": self._get_host_id(instance) or "", + "hostId": self._get_host_id(instance), "image": self._get_image(request, instance), "flavor": self._get_flavor(request, instance, show_extra_specs), @@ -236,10 +234,7 @@ class ViewBuilder(common.ViewBuilder): def _get_host_id(instance): host = instance.get("host") project = str(instance.get("project_id")) - if host: - data = (project + host).encode('utf-8') - sha_hash = hashlib.sha224(data) - return sha_hash.hexdigest() + return utils.generate_hostid(host, project) def _get_addresses(self, request, instance, extend_address=False): context = request.environ["nova.context"] diff --git a/nova/tests/unit/test_utils.py b/nova/tests/unit/test_utils.py index 210e5b7aaebc..9607814e6996 100644 --- a/nova/tests/unit/test_utils.py +++ b/nova/tests/unit/test_utils.py @@ -239,6 +239,16 @@ class GenericUtilsTestCase(test.NoDBTestCase): utils.ssh_execute('remotehost', 'ls', '-l') mock_method.assert_called_once_with(*expected_args) + def test_generate_hostid(self): + host = 'host' + project_id = '9b9e3c847e904b0686e8ffb20e4c6381' + hostId = 'fa123c6f74efd4aad95f84096f9e187caa0625925a9e7837b2b46792' + self.assertEqual(utils.generate_hostid(host, project_id), hostId) + + def test_generate_hostid_with_none_host(self): + project_id = '9b9e3c847e904b0686e8ffb20e4c6381' + self.assertEqual(utils.generate_hostid(None, project_id), '') + class TestCachedFile(test.NoDBTestCase): @mock.patch('os.path.getmtime', return_value=1) diff --git a/nova/utils.py b/nova/utils.py index 66ce57738dd7..748ec5f6c5f5 100644 --- a/nova/utils.py +++ b/nova/utils.py @@ -1380,3 +1380,21 @@ def supports_direct_io(dirpath): pass return hasDirectIO + + +def generate_hostid(host, project_id): + """Generate an obfuscated host id representing the host. + + This is a hashed value so will not actually look like a hostname, and is + hashed with data from the project_id. + + :param host: The name of the compute host. + :param project_id: The UUID of the project. + :return: An obfuscated hashed host id string, return "" if host is empty + """ + if host: + data = (project_id + host).encode('utf-8') + sha_hash = hashlib.sha224(data) + return sha_hash.hexdigest() + else: + return ""