def _generate_hostname(pattern, number): """Generates hostname based on pattern Replaces '#' char in pattern with supplied number, if no pattern is supplied generates short and unique name for the host. :param pattern: hostname pattern :param number: number to replace with in pattern :return: hostname """ global _random_string_counter if pattern: # NOTE(kzaitsev) works both for unicode and simple strings in py2 # and works as expected in py3 return pattern.replace('#', str(number)) counter = _random_string_counter or 1 # generate first 5 random chars prefix = ''.join(random.choice(string.ascii_lowercase) for _ in range(5)) # convert timestamp to higher base to shorten hostname string # (up to 8 chars) timestamp = helpers.int2base(int(time.time() * 1000), 36)[:8] # third part of random name up to 2 chars # (1295 is last 2-digit number in base-36, 1296 is first 3-digit number) suffix = helpers.int2base(counter, 36) _random_string_counter = (counter + 1) % 1296 return prefix + timestamp + suffix
def _generate_hostname(pattern, number): """Replace '#' char in pattern with supplied number, if no pattern is supplied generate short and unique name for the host. :param pattern: hostname pattern :param number: number to replace with in pattern :return: hostname """ global _random_string_counter if pattern and isinstance(pattern, types.UnicodeType): return pattern.replace(u'#', unicode(number)) elif pattern: return pattern.replace('#', str(number)) counter = _random_string_counter or 1 # generate first 5 random chars prefix = ''.join(random.choice(string.lowercase) for _ in range(5)) # convert timestamp to higher base to shorten hostname string # (up to 8 chars) timestamp = helpers.int2base(int(time.time() * 1000), 36)[:8] # third part of random name up to 2 chars # (1295 is last 2-digit number in base-36, 1296 is first 3-digit number) suffix = helpers.int2base(counter, 36) _random_string_counter = (counter + 1) % 1296 return prefix + timestamp + suffix
def test_int2base(self): for x in range(30): self.assertEqual("{0:b}".format(x), helpers.int2base(x, 2)) self.assertEqual("{0:o}".format(x), helpers.int2base(x, 8)) self.assertEqual("{0:x}".format(x), helpers.int2base(x, 16))