Make sure no duplicate stack name when creating k8s bay

Change-Id: I2ef6ef9f8cdd317d574312ac591f5e65bf227d2e
Closes-Bug: #1412497
This commit is contained in:
Jay Lau (Guangya Liu) 2015-01-19 21:21:01 -05:00
parent 92e7ca62c5
commit d2dede5723
4 changed files with 142 additions and 4 deletions

59
magnum/common/short_id.py Normal file
View File

@ -0,0 +1,59 @@
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Utilities for creating short ID strings based on a random UUID.
The IDs each comprise 12 (lower-case) alphanumeric characters.
"""
import base64
import uuid
import six
from magnum.openstack.common._i18n import _
def _to_byte_string(value, num_bits):
"""Convert an integer to a big-endian string of bytes with padding.
Padding is added at the end (i.e. after the least-significant bit) if
required.
"""
shifts = six.moves.xrange(num_bits - 8, -8, -8)
byte_at = lambda off: (value >> off if off >= 0 else value << -off) & 0xff
return ''.join(chr(byte_at(offset)) for offset in shifts)
def get_id(source_uuid):
"""Derive a short (12 character) id from a random UUID.
The supplied UUID must be a version 4 UUID object.
"""
if isinstance(source_uuid, six.string_types):
source_uuid = uuid.UUID(source_uuid)
if source_uuid.version != 4:
raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)
# The "time" field of a v4 UUID contains 60 random bits
# (see RFC4122, Section 4.4)
random_bytes = _to_byte_string(source_uuid.time, 60)
# The first 12 bytes (= 60 bits) of base32-encoded output is our data
encoded = base64.b32encode(random_bytes)[:12]
return encoded.lower()
def generate_id():
"""Generate a short (12 character), random id."""
return get_id(uuid.uuid4())

View File

@ -17,6 +17,7 @@ from heatclient import exc
from oslo.config import cfg
from magnum.common import clients
from magnum.common import short_id
from magnum import objects
from magnum.openstack.common._i18n import _
from magnum.openstack.common import log as logging
@ -73,8 +74,10 @@ def _create_stack(ctxt, osc, bay):
tpl_files, template = template_utils.get_template_contents(
cfg.CONF.k8s_heat.template_path)
# Make sure no duplicate stack name
stack_name = '%s-%s' % (bay.name, short_id.generate_id())
fields = {
'stack_name': bay.name,
'stack_name': stack_name,
'parameters': bay_definition,
'template': template,
'files': dict(list(tpl_files.items()))

View File

@ -0,0 +1,72 @@
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
import testtools
from magnum.common import short_id
class ShortIdTest(testtools.TestCase):
def test_byte_string_8(self):
self.assertEqual('\xab', short_id._to_byte_string(0xab, 8))
self.assertEqual('\x05', short_id._to_byte_string(0x05, 8))
def test_byte_string_16(self):
self.assertEqual('\xab\xcd', short_id._to_byte_string(0xabcd, 16))
self.assertEqual('\x0a\xbc', short_id._to_byte_string(0xabc, 16))
def test_byte_string_12(self):
self.assertEqual('\xab\xc0', short_id._to_byte_string(0xabc, 12))
self.assertEqual('\x0a\xb0', short_id._to_byte_string(0x0ab, 12))
def test_byte_string_60(self):
val = 0x111111111111111
byte_string = short_id._to_byte_string(val, 60)
self.assertEqual('\x11\x11\x11\x11\x11\x11\x11\x10', byte_string)
def test_get_id_string(self):
id = short_id.get_id('11111111-1111-4111-bfff-ffffffffffff')
self.assertEqual('ceirceirceir', id)
def test_get_id_uuid_1(self):
source = uuid.UUID('11111111-1111-4111-bfff-ffffffffffff')
self.assertEqual(0x111111111111111, source.time)
self.assertEqual('ceirceirceir', short_id.get_id(source))
def test_get_id_uuid_f(self):
source = uuid.UUID('ffffffff-ffff-4fff-8000-000000000000')
self.assertEqual('777777777777', short_id.get_id(source))
def test_get_id_uuid_0(self):
source = uuid.UUID('00000000-0000-4000-bfff-ffffffffffff')
self.assertEqual('aaaaaaaaaaaa', short_id.get_id(source))
def test_get_id_uuid_endianness(self):
source = uuid.UUID('ffffffff-00ff-4000-aaaa-aaaaaaaaaaaa')
self.assertEqual('aaaa77777777', short_id.get_id(source))
def test_get_id_uuid1(self):
source = uuid.uuid1()
self.assertRaises(ValueError, short_id.get_id, source)
def test_generate_ids(self):
allowed_chars = 'abcdefghijklmnopqrstuvwxyz234567'
ids = [short_id.generate_id() for i in range(25)]
for id in ids:
self.assertEqual(12, len(id))
self.assertFalse(id.translate(None, allowed_chars))
self.assertEqual(1, ids.count(id))

View File

@ -137,18 +137,22 @@ class TestBayK8sHeat(base.BaseTestCase):
parsed_outputs = bay_k8s_heat._parse_stack_outputs(outputs)
self.assertEqual(expected_return_value, parsed_outputs)
@patch('magnum.common.short_id.generate_id')
@patch('heatclient.common.template_utils.get_template_contents')
@patch('magnum.objects.BayModel.get_by_uuid')
@patch('magnum.conductor.handlers.bay_k8s_heat._extract_bay_definition')
def test_create_stack(self,
mock_extract_bay_definition,
mock_objects_baymodel_get_by_uuid,
mock_get_template_contents):
mock_get_template_contents,
mock_generate_id):
expected_stack_name = 'expected_stack_name'
mock_generate_id.return_value = 'xx-xx-xx-xx'
expected_stack_name = 'expected_stack_name-xx-xx-xx-xx'
expected_number_of_minions = 1
expected_template_contents = 'template_contents'
exptected_files = []
dummy_bay_name = 'expected_stack_name'
mock_tpl_files = mock.MagicMock()
mock_tpl_files.items.return_value = exptected_files
@ -160,7 +164,7 @@ class TestBayK8sHeat(base.BaseTestCase):
mock_osc = mock.MagicMock()
mock_osc.heat.return_value = mock_heat_client
mock_bay = mock.MagicMock()
mock_bay.name = expected_stack_name
mock_bay.name = dummy_bay_name
mock_bay.node_count = expected_number_of_minions
bay_k8s_heat._create_stack({}, mock_osc, mock_bay)