Follow hostname RFCs

Updated hostname sanitization method to more closely follow RFC-952
and RFC-1123. Also moved it to nova.utils, where it seems to fit
better.

Fixes bug 885374

(Patch Set 1) Updated hostname sanitization with more efficient and
              [opinion] more readable implementation.

Change-Id: I60d7ee89867c05950bec1fd53b072a1c6247ebea
This commit is contained in:
Brian Lamar 2011-11-09 18:16:24 -05:00
parent 1ef2796c2f
commit c969b0018d
2 changed files with 37 additions and 0 deletions

View File

@ -1237,6 +1237,30 @@ class ComputeAPITestCase(BaseTestCase):
db.instance_destroy(self.context, instance_id)
def test_hostname_create(self):
"""Ensure instance hostname is set during creation."""
inst_type = instance_types.get_instance_type_by_name('m1.tiny')
(instances, _) = self.compute_api.create(self.context,
inst_type,
None,
display_name='test host')
self.assertEqual('test-host', instances[0]['hostname'])
def test_hostname_update(self):
"""Ensure instance hostname is set during an update."""
instance_id = self._create_instance({"display_name": "test host"})
instance = db.instance_get(self.context, instance_id)
expected_hostname = 'test-host'
actual = self.compute_api.update(self.context,
instance_id,
**dict(instance))
self.assertEqual(expected_hostname, actual['hostname'])
db.instance_destroy(self.context, instance_id)
def test_set_admin_password(self):
"""Ensure instance can have its admin password set"""
instance_id = self._create_instance()

View File

@ -1061,3 +1061,16 @@ def total_seconds(td):
else:
return ((td.days * 86400 + td.seconds) * 10 ** 6 +
td.microseconds) / 10.0 ** 6
def sanitize_hostname(hostname):
"""Return a hostname which conforms to RFC-952 and RFC-1123 specs."""
if isinstance(hostname, unicode):
hostname = hostname.encode('latin-1', 'ignore')
hostname = re.sub('[ _]', '-', hostname)
hostname = re.sub('[^\w.-]+', '', hostname)
hostname = hostname.lower()
hostname = hostname.strip('.-')
return hostname