Extract generate_hostid method into utils.py

This would be used in instance action API to show the hostId
to non-admin user.

This patch propose to extract the generate_hostid method
into utils.

trivial fix

Change-Id: I00d29e9fd80e6b8f7ba3bbd8e82dde9d4cb1522f
This commit is contained in:
Yikun Jiang 2018-03-22 20:16:41 +08:00
parent cbf02e050e
commit 7500462bc3
3 changed files with 30 additions and 7 deletions

View File

@ -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"]

View File

@ -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)

View File

@ -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 ""